我正在尝试为具有基本属性和"一个或另一个"属性的对象创建一个类型。我尝试使用并集和交集类型来实现这一点,但我的知识有限,我似乎无法弄清楚。
我希望流可以看到第一个属性并推断不应该允许另一个属性(目前我什至无法让流允许(。
我的尝试:
type Base = {
name: string,
age: number
}
type Teacher = Base & {
teacherId: number,
}
type Student = Base & {
studentId: number
}
type Person = Student | Teacher;
const person: Person = {
name: "John",
age: 20,
studentId: 000,
teacherId: 111
}
console.log(person.age); // Works
console.log(person.studentId); // Fails?
console.log(person.teacherId); // Fails?
试试看
默认情况下
,Flow 中的对象是不精确的(尽管团队已经指出此行为可以更改(。这意味着打字
const teacher: Teacher = {
name: 'Alexa',
age: 41,
teacherId: 2,
studentId: 3
}
是完全有效的,因为它具有三个必需的属性name
、age
和 teacherId
。有关详细信息,请参阅宽度子类型。
要使 Flow 针对其他属性发出警告,您需要使用精确的对象(用 {| ... |}
表示(。Flow 现在会抱怨同时使用 studentId
和 teacherId
.
type Base = {|
name: string,
age: number
|}
type Teacher = {|
...Base,
teacherId: number,
|}
type Student = {|
...Base,
studentId: number
|}
type Person = Student | Teacher;
const person: Person = {
name: "John",
age: 20,
studentId: 000,
teacherId: 111
} // Fails
尝试流