英文:
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 = "string" | undefined;
type What<T> = T extends undefined ? "true" : "false";
const no : What<stringUndefined> = "";
no becomes "true" | "false"
instead of what I would expect, "true"
Edit:
strict null checks are enabled
答案1
得分: 3
"string" | undefined
不扩展 undefined
,因为它可以是 "string"
。
但 undefined
扩展 "string" | undefined
,因为联合类型的成员扩展(细化)联合类型。所以:
type StringLiteralOrUndefined = "string" | undefined;
type What<T> = undefined extends T ? true : false;
type X = What<StringLiteralOrUndefined>;
// ^? type X = true
type UnrelatedType = string | number;
type Y = What<UnrelatedType>;
// ^? type Y = false
英文:
"string" | undefined
doesn't extend undefined
, because it can be "string"
.
But undefined
extends "string" | undefined
, because the members of a union extend (refine) the union. So:
type StringLiteralOrUndefined = "string" | undefined;
type What<T> = undefined extends T ? true : false;
type X = What<StringLiteralOrUndefined>;
// ^? type X = true
type UnrelatedType = string | number;
type Y = What<UnrelatedType>;
// ^? type Y = false
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论