TypeScript:接口属性要求另一个属性为 true

Vin*_*rma 7 javascript angularjs typescript reactjs redux

如果foo 为 false,如何将keys:定义a, b, c, bar未定义/空/可选类型?换句话说,仅当foo 为 true时,我才需要强制使用这些属性。

interface ObjectType {
  foo: boolean;
  a: number;
  y: string;
  c: boolean;
  bar?: { x: number; y: string; z: boolean };
}
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

小智 10

我认为最直接的方法是简单地使用联合类型。

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;
Run Code Online (Sandbox Code Playgroud)

当然,如果需要的话,您可以抽象出重复的属性,以节省在将随时间变化的类型上的输入。

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;
Run Code Online (Sandbox Code Playgroud)

您还可以免费获得类型推断。

if (type.foo) {
  // im the required type!
  // type.a would be boolean.
} else {
  // im the optional type.
  // type.a would be boolean?
}
Run Code Online (Sandbox Code Playgroud)