如何定义键:a, b, c, bar
作为未定义/空/可选输入如果 foo 是假的 ?换句话说,我需要这些属性是 必填 仅当 foo 是真的 .
interface ObjectType {
foo: boolean;
a: number;
y: string;
c: boolean;
bar?: { x: number; y: string; z: boolean };
}
谢谢! :)
最佳答案
我认为最直接的方法是简单地使用联合类型。
interface RequiredObjectType {
foo: true;
a: number;
y: string;
c: boolean;
bar: { x: number; y: string; z: boolean };
}
interface OptionalObjectType {
foo: false;
a?: number;
y?: string;
c?: boolean;
bar?: { x: number; y: string; z: boolean };
}
type AnyObjectType = RequiredObjectType| OptionalObjectType;
如果需要,您当然可以将重复的属性抽象出来,以节省对将随时间更改的类型的输入。interface ObjectTypeValues {
a: number;
y: string;
c: boolean;
bar: { x: number; y: string; z: boolean };
}
interface RequiredObjectType extends ObjectTypeValues {
foo: true
}
interface OptionalObjectType extends Partial<ObjectTypeValues> {
foo: false
}
type AnyObjectType = RequiredObjectType | OptionalObjectType;
您还将免费获得类型推断。if (type.foo) {
// im the required type!
// type.a would be boolean.
} else {
// im the optional type.
// type.a would be boolean?
}
关于javascript - TypeScript:一个接口(interface)属性需要另一个属性为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64933861/