使用 Typescript 联合获取类型错误
Getting error with type using Typescript union
type myType = { subtitle: string, title: string } | {};
const someVar: myType = { title: 'some-title', subtitle: 'some subtitle'}
const myTitle: string = someVar?.title;
当我尝试从 someVar
对象访问 title
值时出现此类型错误。现在,我不明白的是为什么会出现这种类型错误。我检查了 documentation 但我不明白它的含义。 Union 意味着我可以指定可能的类型,但这里的行为似乎有所不同。知道为什么吗
Property 'title' does not exist on type '{} | { subtitle: string; title: string; }'.
Property 'title' does not exist on type '{}'.ts(2339)
Now, what I don't understand is why wouldI get this type error.
因为{}
没有一个叫做title
的属性,而你说someVar
的类型是myType
,这是 { subtitle: string, title: string }
或 {}
。由于它可能是 {}
,您必须首先确保它在那里才能访问 title
。来自 the handbook:
TypeScript will only allow you to do things with the union if that thing is valid for every member of the union.
访问 title
对 {}
无效,仅 { subtitle: string, title: string }
.
要使用 title
,可以使用类型保护来缩小类型(关于缩小 here in the handbook 的详细信息):
if ("title" in someVar) {
// ...you can use `someVar.title` (and/or `someVar.subtitle`) here...
}
在 if
正文中,TypeScript 知道 someVar
的类型是 { subtitle: string, title: string }
,而不是 {}
,这要感谢条件。
that 也可能对通读有用,关于如何将额外的 属性 检查应用于联合和 StrictUnion
标志。
type myType = { subtitle: string, title: string } | {};
const someVar: myType = { title: 'some-title', subtitle: 'some subtitle'}
const myTitle: string = someVar?.title;
当我尝试从 someVar
对象访问 title
值时出现此类型错误。现在,我不明白的是为什么会出现这种类型错误。我检查了 documentation 但我不明白它的含义。 Union 意味着我可以指定可能的类型,但这里的行为似乎有所不同。知道为什么吗
Property 'title' does not exist on type '{} | { subtitle: string; title: string; }'.
Property 'title' does not exist on type '{}'.ts(2339)
Now, what I don't understand is why wouldI get this type error.
因为{}
没有一个叫做title
的属性,而你说someVar
的类型是myType
,这是 { subtitle: string, title: string }
或 {}
。由于它可能是 {}
,您必须首先确保它在那里才能访问 title
。来自 the handbook:
TypeScript will only allow you to do things with the union if that thing is valid for every member of the union.
访问 title
对 {}
无效,仅 { subtitle: string, title: string }
.
要使用 title
,可以使用类型保护来缩小类型(关于缩小 here in the handbook 的详细信息):
if ("title" in someVar) {
// ...you can use `someVar.title` (and/or `someVar.subtitle`) here...
}
在 if
正文中,TypeScript 知道 someVar
的类型是 { subtitle: string, title: string }
,而不是 {}
,这要感谢条件。
StrictUnion
标志。