当我注意到虽然没有Nullable类型(或者没有?)时,我在TypeScript中寻找类似于Nullable类型的东西,但是在中定义了 NonNullable 类型:
C:\ Program Files \ Microsoft VS Code \ resources \ app \ extensions \ node_modules \ typescript \ lib \ lib.es6.d.ts
NonNullable 的定义是:
/**
* Exclude null and undefined from T
*/
type NonNullable<T> = T extends null | undefined ? never : T;
有人可以解释(或指向相关文档)这个定义的含义是什么?我无法找到有关此文档的文档。具体来说,我找不到?
运算符和never
关键字在通用约束的上下文中的含义。
我在同一个文件中找到了其他类似的定义:
/**
* Exclude from T those types that are assignable to U
*/
type Exclude<T, U> = T extends U ? never : T;
/**
* Extract from T those types that are assignable to U
*/
type Extract<T, U> = T extends U ? T : never;
答案 0 :(得分:0)
有人向您指出了条件类型的方向,这是您问题的第二部分,但对于偶然发现此问题的其他人,NonNullable的反义词将是T |。空| undefined,基本上只是说可以将其定义为T,也可以为null或未定义,您可以在此处https://www.typescriptlang.org/docs/handbook/advanced-types.html#nullable-types
了解更多信息