本文介绍了具有XOR,{bar:string} xor {can:number}的TypeScript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么说我希望一个接口是一个或另一个,而不是两者或两者都不是?
How do I say that I want an interface to be one or the other, but not both or neither?
interface IFoo {
bar: string /*^XOR^*/ can: number;
}
推荐答案
您可以将联合类型与 never
类型来实现此目标:
You can use union types along with the never
type to achieve this:
type IFoo = {
bar: string; can?: never
} | {
bar?: never; can: number
};
let val0: IFoo = { bar: "hello" } // OK only bar
let val1: IFoo = { can: 22 } // OK only can
let val2: IFoo = { bar: "hello", can: 22 } // Error foo and can
let val3: IFoo = { } // Error neither foo or can
这篇关于具有XOR,{bar:string} xor {can:number}的TypeScript接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!