有没有办法定义一个 Typescript interface,它允许对象中的 2 个可选键之一或没有它们,但不能同时允许两者?
这是我试图实现的简化示例:
const example1 = { foo: 'some string' }; //should pass - can have only "foo: string"
const example2 = { bar: 42 }; // should pass - can have only "bar: number"
const example3 = {}; // should pass - both foo and bar are optional
const example4 = { foo: 'some string', bar: 42 }; // should throw a Typescript error - can't have both foo and bar simultaneously;
Run Code Online (Sandbox Code Playgroud)
附注。解决方案应该是一个interface而不是一个,type因为在我的用例中它是extends另一个interface
type是同构的interface,你可以加入这两个结构。下面通过类型并集和交集实现,还添加了示例接口以显示其运行良好,&相当于extends. 考虑:
interface OtherInterface {
field?: string
}
type Example = ({
foo: string
bar?: never
} | {
foo?: never
bar: number
} | {
[K in any]: never
}) & OtherInterface
const example1: Example = { foo: 'some string' }; // ok
const example2: Example = { bar: 42 }; // ok
const example3: Example = {}; // ok
const example4: Example = { foo: 'some string', bar: 42 }; // error
Run Code Online (Sandbox Code Playgroud)
解决方案很冗长,但符合您的需要。一些解释:
bar?: never 用于阻止具有具有此类字段的值的可能性& OtherInterface 有完全相同的结果 extends OtherInterface{[K in any]: never} - 代表空对象 {}