gpt4 book ai didi

typescript - TypeScript 中 NonNullable 的定义

转载 作者:行者123 更新时间:2023-12-04 12:01:12 32 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Conditional types in TypeScript

(4 个回答)


12 个月前关闭。




我在 TypeScript 中寻找类似 Nullable 类型的东西时,我注意到虽然没有 Nullable 类型(或者是否存在?),但有一个 NonNullable类型定义在:
C:\Program Files\Microsoft VS Code\resources\app\extensions\node_modules\typescript\lib\lib.es6.d.tsNonNullable的定义是:

/**
* 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;

最佳答案

有人向您指出了条件类型的方向,这是您问题的第二部分,但对于其他任何偶然发现此问题的人来说,这与 NonNullable<T> 正好相反。将是 T | null | undefined ,基本上只是说可以定义为T或者它可以是 nullundefined ,您可以在此处阅读更多相关信息 https://www.typescriptlang.org/docs/handbook/advanced-types.html#nullable-types

关于typescript - TypeScript 中 NonNullable<T> 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50588873/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com