typescript如何实现有条件的可选属性

160 阅读1分钟

有群友提出了这样一个问题: typescript如何实现有条件的可选属性?

interface Test {
a?:boolean;
b?:any
}

a、b默认都可选,但当a有值时,让b成为必填项。应该如何实现? 在 TypeScript 中,可以通过使用联合类型和条件类型来实现有条件的可选属性。具体来说,你可以定义两个接口,一个用于 aundefined 的情况,另一个用于 a 有值的情况。然后使用联合类型将它们组合起来。

下面是一个实现示例:

interface TestA {
  a?: false; // 当 a 为 false 或 undefined 时,b 是可选的
  b?: any;
}

interface TestB {
  a: true; // 当 a 为 true 时,b 是必填的
  b: any;
}

type Test = TestA | TestB;

// 示例用法
const example1: Test = {
  a: false,
  // b 是可选的
};

const example2: Test = {
  a: true,
  b: "This is required", // b 是必填的
};

// 这个示例会报错,因为 b 是必填的
const example3: Test = {
  a: true,
  // b: "This is required" // 如果没有 b,会报错
};

// 这个示例会报错,如果没有提供 `a`,但提供了 `b`,会导致类型错误
const example4: Test = {
  // a: false,
  b: "This is optional", // b 是可选的
};
  1. 接口 TestA:

    • afalseundefined 时,b 是可选的。
  2. 接口 TestB:

    • atrue 时,b 是必填的。
  3. 联合类型 Test:

    • 通过 TestA | TestB 来组合这两种情况。
  • example1afalseb 是可选的。
  • example2atrueb 是必填的。
  • example3:如果 atrue,但没有提供 b,会导致类型错误。
  • example4:如果没有提供 a,但提供了 b,会导致类型错误。

这样就实现了根据 a 的值来决定 b 是否必填的逻辑。