type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2 why??? how to understand?
type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2
type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1
type SomeUnion = 'a' | 'b'
type UnionDistribute<T> = T extends 'a' ? 1 : 2
type t0 = UnionDistribute<SomeUnion> // => 1 | 2 // any work like an union
Why any extends 'a' ? 1: 2
give 1 | 2
,这项工作作为一个工会。我试图用谷歌寻找一些解释,但失败了。
操场 https://www.typescriptlang.org/play?#code/C4TwDgpgBAKhDOwCCA7EUC8UCGaoQA9gIUATeKAcm0qgH4oBGKALigCYoB6LzAPiZQAPhyhQA7gAsQdWVEkB7cVGAKoAVzIQATolyk6AKFCRYCYAFUUAaxRKUmDTbviHhYmQrVaDZm048-BzG4NBwiADKwNoAligA5kiO3vhEJORUNPSC-ty8GAKMhiGmEQoAthBWMQoOWCkilABGlCXQ1bUAIjGIsU3qxAA8MAJYMKkeGSm+rMEm0MAADI4dKN29Mf1DZZWrAnlBzCKcB7jo4gra1lAANjHW0LhONShAA
See 微软/TypeScript#40049 https://github.com/microsoft/TypeScript/issues/40049对于这个问题的权威答案,尽管我认为它并没有阐明根本原因。
具体来说这条评论 https://github.com/microsoft/TypeScript/issues/40049#issuecomment-674207665:
@杰克-威廉姆斯 https://github.com/jack-williams2020 年 8 月 14 日发表评论:
这在源代码之外没有特别详细的记录,但在检查器中您会在相关位置找到:
// Return union of trueType and falseType for 'any' since it matches anything
if (checkType.flags & TypeFlags.Any) {
So any
被视为匹配两个分支的通配符。
现在 https://raw.githubusercontent.com/microsoft/TypeScript/88d8d1cceeb0fa83d849f9b9f374c59e9a33b7a4/src/compiler/checker.ts你可以在第 15239 行找到代码(GitHub 不会让你链接到像这个一样大的文件中的特定行),它是在这次提交 https://github.com/microsoft/TypeScript/pull/21316/commits/9598acd47702e2e8dee9a43d696d88b2730a2c6b inside 微软/TypeScript#21316 https://github.com/microsoft/TypeScript/pull/21316,实施的拉取请求条件类型 https://www.typescriptlang.org/docs/handbook/2/conditional-types.html首先。只要条件类型存在,情况就一直如此。
这是您最接近“为什么”会发生这种情况的信息。官方的回答是“因为它匹配任何东西”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)