条件类型检查未定义

huangapple go评论49阅读模式
英文:

Conditional type check for undefined

问题

以下是代码的翻译部分:

type stringUndefined = "string" | undefined;

type What<T> = T extends undefined ? "true" : "false";

const no: What<stringUndefined> = "";

no 变成了 "true" | "false",而不是我所期望的 "true"

英文:

For the code

type stringUndefined = &quot;string&quot; | undefined;

type What&lt;T&gt; = T extends undefined ? &quot;true&quot; : &quot;false&quot;;

const no : What&lt;stringUndefined&gt; = &quot;&quot;;

no becomes &quot;true&quot; | &quot;false&quot; instead of what I would expect, &quot;true&quot;

TS-Playground

条件类型检查未定义

Edit:

strict null checks are enabled

答案1

得分: 3

&quot;string&quot; | undefined 不扩展 undefined,因为它可以是 &quot;string&quot;

undefined 扩展 &quot;string&quot; | undefined,因为联合类型的成员扩展(细化)联合类型。所以:

type StringLiteralOrUndefined = &quot;string&quot; | undefined;

type What&lt;T&gt; = undefined extends T ? true : false;

type X = What&lt;StringLiteralOrUndefined&gt;;
//   ^? type X = true

type UnrelatedType = string | number;

type Y = What&lt;UnrelatedType&gt;;
//   ^? type Y = false

Playground

英文:

&quot;string&quot; | undefined doesn't extend undefined, because it can be &quot;string&quot;.

But undefined extends &quot;string&quot; | undefined, because the members of a union extend (refine) the union. So:

type StringLiteralOrUndefined = &quot;string&quot; | undefined;

type What&lt;T&gt; = undefined extends T ? true : false;

type X = What&lt;StringLiteralOrUndefined&gt;;
//   ^? type X = true

type UnrelatedType = string | number;

type Y = What&lt;UnrelatedType&gt;;
//   ^? type Y = false

Playground

huangapple
  • 本文由 发表于 2023年2月9日 00:22:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定