【发布时间】:2017-01-05 21:53:01
【问题描述】:
给定以下类型:
interface FullName {
fullName?: string
}
interface Name {
firstName: string
lastName: string
}
type Person = FullName | Name;
const p1: Person = {};
const p2: Person = { fullName: 'test' };
const p3: Person = { firstName: 'test' }; // Does not throw
const p4: Person = { badProp: true }; // Does throw, as badProp is not on FullName | Name;
我预计p3 会导致编译器错误,因为firstName 在没有lastName 的情况下存在,但它不会——这是错误还是预期?
此外,将 FullName.fullName 设为必需会导致 p3(和 p1)导致错误。
【问题讨论】:
-
可能是一个单独的问题,但有没有办法强制执行可选联合?也就是说,假设
FullName确实需要fullName。有没有办法强制Person要求 (fullName) 或 (firstName和lastName) 或都不要求?
标签: typescript