题目描述
TS中是怎么实现接口的重载入?
相关代码
type ItemProps = {
a: string;
b?: boolean;
c?: string;
}
const arr: ItemProps[] = [
{
a: 'demo',
b: true,
c: 'test'
},
{
a: 'demo2'
}
]
在上面定义中,怎么定义ItemProps
类型才能达到: 如果b
属性存在,则c
属性必需存在 的效果
期待结果
const arr: ItemProps[] = [
{
a: 'demo',
b: true,
c: 'test'
},
{
a: 'demo2',
b: true, // 类型报错,因为存在b属性,但是缺少c
}
];
Playground
把条件改成:
如果b属性存在,则c必须存在,但是c属性存在,b可以不存在。
总结一下,就是 c 必须存在,b 可选存在。
只要修改下
RequireOrExcludeKeys
的参数,以及Required<Pick<T, Keys>>
。Playground