【发布时间】:2019-09-13 04:34:03
【问题描述】:
为什么这不会导致 TS 错误? TS playground
type T = { a: string } | { b: string }
const obj: T = {
a: 'a',
b: 'd',
}
【问题讨论】:
标签: typescript
为什么这不会导致 TS 错误? TS playground
type T = { a: string } | { b: string }
const obj: T = {
a: 'a',
b: 'd',
}
【问题讨论】:
标签: typescript
为了获得互斥性和多余的财产检查,一种解决方法是这样做
export type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
export type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type T = XOR<{ a: string }, { b: string }>
const obj: T = {
a: 'a',
} // passes
const obj1: T = {
b: 'b',
} // passes
const obj2: T = {
a: 'a',
b: 'b',
} // fails
【讨论】:
因为唯一会导致 TS 抱怨的是excess property check,而对于非区分联合类型则不会这样做。 There's open issue for that,2017 年 12 月 22 日报道。
另见Union type does not act as mutual exclusion,答案是“它从未打算这样做”。
【讨论】: