繁体   English   中英

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

[英]TypeScript: an interface property requires another property to be true

如果foo 为 false a, b, c, bar我如何定义键: a, b, c, barundefined/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?
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM