typescript - 从可空类型中提取不可空类型定义

标签 typescript types null typescript-generics

假设我有以下由外部工具生成的界面:

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 Playground 仍然给我 Fox 类型定义为 type Fox = { whatTheySaid: string; } | null 而不是 type Fox = { whatTheySaid: string; }

这可能吗?我哪里错了?

谢谢

最佳答案

NonNullable<Type>

type Fox = NonNullable<Animals["fox"]>;

实现:

/**
 * Exclude null and undefined from T
 */
type NonNullable<T> = T extends null | undefined ? never : T;

关于typescript - 从可空类型中提取不可空类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63671713/

相关文章:

javascript - Angularjs:使用数据动态加载 View 中的指令

nhibernate - 操作数类型冲突 : bigint is incompatible with time

MySQL 使用 LIKE 和 WHERE 选择

javascript - getAttribute不存在时返回值

javascript - Eslint/Tslint 配置帮助(不包括文件)

typescript - Visual Studio 2019 : Not showing Typescript Intellisence

html - angular html中输入文本字段的对齐

haskell - 函数签名声明中集合可以是 "opened"吗?

python - 如何在 cython 中指定列表和元组类型

C++ 链表/节点模板指针在方法返回后不会保持 NULL