vas*_*kch 2 null types typescript typescript-generics
假设我有一个由外部工具生成的以下界面:
\ninterface Animals {\n turtle: { shellHardness: number };\n fox: { whatDidItSay: string } | null;\n}\nRun Code Online (Sandbox Code Playgroud)\n我想Animals为乌龟和狐狸定义(从中提取)类型,但不\xe2\x80\xa6| null为狐狸定义类型。这对乌龟来说很容易,因为没有 null:
type Turtle = Animals["turtle"];\nRun Code Online (Sandbox Code Playgroud)\n但我该如何为狐狸做这件事呢?我想象可能有某种ExtractNullable类型可以消除可为空性:
type Fox = ExtractNullable<Animals, "fox">;\nRun Code Online (Sandbox Code Playgroud)\n不幸的是我无法ExtractNullable正确定义类型。我尝试了以下方法:
type ExtractNullable<T, K extends keyof T> = T[K] extends null ? never : T[K];\nRun Code Online (Sandbox Code Playgroud)\n\xe2\x80\xa6但它不起作用。TypeScript Playground 仍然告诉我类型Fox被定义为type Fox = { whatTheySaid: string; } | null而不是type Fox = { whatTheySaid: string; }
这可能吗?我错了什么?
\n谢谢
\ntype Fox = NonNullable<Animals["fox"]>;
Run Code Online (Sandbox Code Playgroud)
执行:
/**
* Exclude null and undefined from T
*/
type NonNullable<T> = T extends null | undefined ? never : T;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1038 次 |
| 最近记录: |