我定义了两种类型,Team
和Position
。它们都是我在react组件中迭代的数组的一部分。
基于下面在我的map
函数中定义的类型,我看到以下错误。
我看到的错误示例。
类型“位置”上不存在属性“名称”。 [2339]
属性“位置”在类型“团队”上不存在。 [2339]
是否无法检查数组是否包含两种类型?
我的代码如下:
type Team = {
name: string;
city: string;
}
type Position = {
position: number;
}
const Component = () => {
const teamsAndPosition = [
{
name: 'Arsenal',
city: 'London',
},
{
name: 'Everton',
city: 'Liverpool',
},
{
position: 2
}
];
const [list, setList] = useState<Array<Team | Position >>(teams)
list.map((item: Team | Position) => {
return item.name ? (
<div>
// I am seeing an error for these below
<p>{item.name}</p>
<p>{item.city}</p>
</div>
) : (
<p>{item.position}</p>
)
})
}
答案 0 :(得分:2)
在处理可能是两种(或更多)类型之一的变量时,可以在处理对象之前检查对象上是否存在唯一属性,以便打字稿可以推断出它是什么类型。
示例:
myDateObject = in.readSerializable() as Date
在您的情况下(而且我不是React专家),您可以执行以下操作:
interface IObjectYo {
someProp: number
same: boolean
}
interface IDifObjYo {
otherProp: number
same: boolean
}
function example(someArg: IObjectYo | IDifObjYo) {
console.log(someArg.someProp) // tsc complains because someProp doesn't belong to IDifObjYo
if ('someProp' in someArg) {
console.log(someArg.someProp) // tsc knows it must be type IObjectYo because someProp only belongs to IObjectYo
} else {
console.log(someArg.otherProp) // tsc knows this is IDifObjYo because the first condition failed (which means it must be of type IDifObjYo)
}
if ('same' in someArg) {
console.log(someArg.someProp) // make sure the property is indeed unique between the possible types or tsc can't infer
}
}