最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeScript: an interface property requires another property to be true - Stack Overflow

programmeradmin1浏览0评论

How can I define keys: a, b, c, bar as undefined/null/optional type if foo is false? In other words, I need these properties to be mandatory only if foo is true.

interface ObjectType {
  foo: boolean;
  a: number;
  y: string;
  c: boolean;
  bar?: { x: number; y: string; z: boolean };
}

Thanks! :)

How can I define keys: a, b, c, bar as undefined/null/optional type if foo is false? In other words, I need these properties to be mandatory only if foo is true.

interface ObjectType {
  foo: boolean;
  a: number;
  y: string;
  c: boolean;
  bar?: { x: number; y: string; z: boolean };
}

Thanks! :)

Share Improve this question asked Nov 20, 2020 at 17:13 Vinay SharmaVinay Sharma 3,8176 gold badges38 silver badges69 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

I think the most straight forward way is to simply use union types.

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;

You could of course abstract the repeated properties out if needed to save typing on types that will change overtime.

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;

You'll get type inference for free as well.

if (type.foo) {
  // im the required type!
  // type.a would be boolean.
} else {
  // im the optional type.
  // type.a would be boolean?
}
发布评论

评论列表(0)

  1. 暂无评论