打字稿:只有几个接口之一

时间:2020-03-10 10:36:43

标签: typescript types interface union

是否可以声明一个定义几个接口中只有一个有效的接口的类型?

例如:

interface Bar {
    properties: Record<string,any>
    construct?: () => void
    convert?: () => void
}

interface Foo {
    type?: string
    optional?: boolean
}

type FooBar = Bar | Foo;


//should not work
({
    properties: {},
    type: 'number'
} as FooBar);

//should not work
({
    convert: () => {},
    type: 'number'
} as FooBar);

//should work
({
    type: 'number',
    optional: true
} as FooBar);

//should work
({
    properties: {},
    convert: () => {}
} as FooBar);

我想在定义属性“ properties”时实现,只能添加接口“ Bar”的可选属性。并且,当未定义属性“ properties”时,只能使用接口“ Foo”的属性。 我用Union进行了尝试,但是也可以混合使用接口。

我该如何解决问题,甚至有可能吗?

1 个答案:

答案 0 :(得分:0)

我认为唯一的方法是使用Discriminated Unions。像这样:

interface Foo {
    type: "foo";
    foo: number;
}

interface Bar {
    type: "bar";
    bar: string;
}

type FooBar = Foo | Bar;

let bar: FooBar = {
    type: "bar",
    foo: 42 // error
}

Playground link