您已更新您的问题,说 multi 应该是可选的(默认为 false)。这排除了有区别的联合(下面水平线下的先前答案)。
我想我会使用你联合在一起的两个接口,以及(如有必要)它们共同拥有的东西的基本接口。当您需要知道选择的类型时,您可能需要类型保护函数。
// Things all MySelects have in common (if you have anything other than `onChange`)
interface MySelectBase {
name: string;
}
// A single-select version of MySelect
interface MySingleSelect extends MySelectBase {
multi?: false;
onChange: (item: string) => void;
}
// A multi-select version of MySelect
interface MyMultiSelect extends MySelectBase {
multi: true;
onChange: (items: string[]) => void;
}
// The unified type
type MySelect = MySingleSelect | MyMultiSelect;
// Type guard function to see whether it's a single select
const isSingleSelect = (select: MySelect): select is MySingleSelect => {
return !select.multi; // !undefined and !false are both true
};
// Type guard function to see whether it's a multi select
const isMultiSelect = (select: MySelect): select is MyMultiSelect => {
return !!select.multi; // !!undefined and !!true are both true
};
创建示例:
const single: MySingleSelect = {
name: "some-single-select-field",
onChange : (item) => { console.log(item); }
};
const multi: MyMultiSelect = {
multi: true,
name: "some-multi-select-field",
onChange : (items) => { console.log(items); }
};
MySelect(组合接口)使用示例:
const useMySelect = (select: MySelect) => {
// No need for a guard on anything but `onChange`
console.log(select.name);
// `onChange` will be a union type until/unless you use a type guard
const onChange = select.onChange;
// ^^^^^^^^−−−−−−−−−− type is `((item: string) => void) | ((items: string[]) => void)`
if (isSingleSelect(select)) {
// It's a MySingleSelect
const onChange = select.onChange;
// ^^^^^^^^−−−−−−−−−− type is `(item: string) => void`
} else {
// It's a MyMultiSelect
const onChange = select.onChange;
// ^^^^^^^^−−−−−−−−−− type is `(items: string[]) => void`
}
};
Playground link
对于那些不需要将multi 设为可选的人来说,这是原始答案:
您可以通过将 MySelect 声明为类型的联合来做到这一点,其中一个与 multi: true,另一个与 multi: false:
type MySelect =
{
multi: true;
onChange: (items: string[]) => void;
}
|
{
multi: false;
onChange: (item: string) => void;
};
然后你得到:
const mySelect: MySelect = {
multi: true,
onChange: (items) => {}
// ^^^^^^^^−−−−−−−−−−− correctly inferred as (items: string[]) => void
};
Playground link
这称为discriminated union:由一个(或多个)字段的类型区分(区分)的类型的联合。
如果您有大量没有变化的其他属性,您可以使用交集将它们添加到可区分联合:
type MySelect =
(
{
multi: true;
onChange: (items: string[]) => void;
}
|
{
multi: false;
onChange: (item: string) => void;
}
)
&
{
the: number;
other: string;
properties: string;
};