作为头衔.我买了一个在线课程,我直到现在都没有时间看.在课程中,它说了类似于TypeScript中不允许的was:
type Name = { name: string }
type Age = { age: number }
type UnionBoth = Name | Age
const test = (union: UnionBoth): void => {
if ('name' in union && 'age' in union) {
union.name
union.age
}
}
但在当前版本5.4.3
上测试后,它没有出现错误.我开始在上一个版本上测试相同的代码并重复它,最后,我在4.8.4
处达到了an error on the Playground:
Property 'name' does not exist on type 'never'.
Property 'age' does not exist on type 'never'.
有什么解释吗?这门课程试图"改变"我的思维模式,说unions 可能不是我们认为的the intuitive way.现在这不是错误,那么正确的心理模型是什么,正确地理解上面的代码?
只是判断了5.4.3
处的代码,函数中的推理类型union
是以下类型:
(parameter) union: Name & Record<"age", unknown>
为什么这里有Record
只为age
房地产?
我目前的心理模型:
- 有两组
Name
和Age
. - 函数的联合
union
可以落入以下三种情况之一:- 只在
Name
. - 只在
Age
. - 它在十字路口,即
Name & Age
.
- 只在
- 通过
if
语句的类型缩小,TypeScript应该理解大小写是3,我们应该能够访问块内的name
和age
.