【发布时间】:2020-12-19 15:02:24
【问题描述】:
假设我有以下由外部工具生成的界面:
interface Animals {
turtle: { shellHardness: number };
fox: { whatDidItSay: string } | null;
}
我想为乌龟和狐狸定义(从Animals 中提取)一个类型,但没有为狐狸定义…| null。乌龟很容易,因为没有空值:
type Turtle = Animals["turtle"];
但是我该如何为狐狸做呢?我想可能有一些 ExtractNullable 类型可以消除可空性:
type Fox = ExtractNullable<Animals, "fox">;
很遗憾,我无法正确定义 ExtractNullable 类型。我尝试了以下方法:
type ExtractNullable<T, K extends keyof T> = T[K] extends null ? never : T[K];
……但它没有用。 TypeScript 操场仍然让我知道 Fox 类型被定义为 type Fox = { whatTheySaid: string; } | null 而不是 type Fox = { whatTheySaid: string; }
这可能吗?我哪里错了?
谢谢
【问题讨论】:
标签: typescript types null typescript-generics