如果 foo 为 false,我该如何将键:a,b,c,bar
定义为 undefined/null/optional 类型?换句话说,只有当 foo 为 true 时,这些属性才是 必需的。
interface ObjectType {
foo: boolean;
a: number;
y: string;
c: boolean;
bar?: { x: number; y: string; z: boolean };
}
谢谢! :)
如果 foo 为 false,我该如何将键:a,b,c,bar
定义为 undefined/null/optional 类型?换句话说,只有当 foo 为 true 时,这些属性才是 必需的。
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?
}