TypeScript:一个接口属性需要另一个属性为真

7

如果 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 };
}

谢谢! :)
1个回答

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;

当然,如果需要在会随时间变化的类型上节省输入,你可以将重复的属性抽象出来。
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?
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接