“值”和“ defaultValue”不能同时出现

时间:2019-06-23 15:16:05

标签: typescript

我希望“ value”和“ defaultValue”不会同时出现,但是我的代码没有达到效果。

type T = { 
    value: string;
    // other props
 } | { 
    defaultValue: string;
    // other props
 };
 let t: T = {value: '', defaultValue: ''}; // why can it appear at the same time

预期的行为:

“值”和“默认值”不能同时出现。

实际行为:

“值”和“默认值”同时出现。

1 个答案:

答案 0 :(得分:1)

这可以通过XOR类型实现,您可以像这样实现:

type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }

type XOR<T, U> = (T | U) extends object
    ? (Without<T, U> & U) | (Without<U, T> & T)
    : T | U

然后,您将像这样定义类型T:

type OtherProps = {
    // other props 
}
type T = OtherProps & XOR<{ value: string }, { defaultValue: string }>

(从TypeScript interface with XOR, {bar:string} xor {can:number}窃取)