【发布时间】:2020-04-14 01:04:38
【问题描述】:
我是打字稿的新手。我一直在玩联合和交叉类型的形状,并遇到了一些我没想到的东西......
如果我创建两个形状如下:
type Person = {
name: string,
occupation?: string
}
type Animal = {
name: string
gestationPeriodDays: number
}
然后我创建这两个形状的并集和一个交叉点,就像这样......
type AnimalUnionPerson = Animal | Person
let humanzeeAllFields: AnimalUnionPerson = {
name: "Humanzee",
gestationPeriodDays: 60,
occupation: "Banana Farmer"
}
type AnimalIntersectPerson = Animal & Person
let animalIntersectPerson = {
name: "Shape Intersect",
gestationPeriodDays: 24,
occupation: "Data Scientist"
}
然后我创建了一个简单的函数,将交集类型作为参数...
function printOutIntersection(toPrint: AnimalIntersectPerson) {
console.log(toPrint.name)
console.log(toPrint.occupation) // With union of shapes, no need for User Defined Type Guard
console.log(toPrint.gestationPeriodDays)
}
现在我可以将animalIntersectPerson 传递给函数,但不能将humanzeeAllFields 作为参数传递给函数,即使形状本身具有相同的字段。我希望能够给出由 TypeScript 执行的结构类型检查。谁能解释一下为什么会这样?
【问题讨论】:
标签: typescript