考虑这些定义:
interface A {
id?: string;
name?: string;
}
interface BaseLabel<B extends Parent, Parent extends A> {
keyStr?: keyof Omit<B, keyof Parent> & string;
}
interface RequiredLabel<B extends Parent, Parent extends A> extends BaseLabel<B, A> {
label: string;
}
interface OptionalLabel<B extends Parent, Parent extends A> extends BaseLabel<B, A> {
label?: string;
}
type Final<B extends Parent, Parent extends A> = RequiredLabel<B, Parent> | OptionalLabel<B, Parent>
我需要细化
Final
类型,以便父键应该具有必需的标签(基于 RequiredLabel
),而所有其他 B 键都可以带有可选标签(基于 OptionalLabel
)。
interface Parent extends A {
value?: string;
}
interface child extends Parent {
isDate?: boolean;
}
const fields: Final[] = [
{id: '1', name: '1', isDate: true},
{id: '2', name: '2', isDate: true, label: 'label 2'},
{id: '3', name: '3', value: '3', label: 'label 3'},
];
所有与家长相关的记录都必须有强制性标签,而其他记录则可以没有。
任何人都可以帮我缩小范围吗?
这是对我有用的解决方案:
interface RequiredLabel<B extends Parent, Parent extends A> {
keyStr: keyof Parent & string;
label: string;
}
interface OptionalLabel<B extends Parent, Parent extends A> {
keyStr: keyof Omit<B, keyof Parent> & string;
label?: string;
}
type Final<B extends Parent, Parent extends A> = RequiredLabel<B, Parent> | OptionalLabel<B, Parent>