有群友提出了这样一个问题: typescript如何实现有条件的可选属性?
interface Test {
a?:boolean;
b?:any
}
a、b默认都可选,但当a有值时,让b成为必填项。应该如何实现?
在 TypeScript 中,可以通过使用联合类型和条件类型来实现有条件的可选属性。具体来说,你可以定义两个接口,一个用于 a 为 undefined 的情况,另一个用于 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 是可选的
};
-
接口
TestA:- 当
a为false或undefined时,b是可选的。
- 当
-
接口
TestB:- 当
a为true时,b是必填的。
- 当
-
联合类型
Test:- 通过
TestA | TestB来组合这两种情况。
- 通过
example1:a为false,b是可选的。example2:a为true,b是必填的。example3:如果a为true,但没有提供b,会导致类型错误。example4:如果没有提供a,但提供了b,会导致类型错误。
这样就实现了根据 a 的值来决定 b 是否必填的逻辑。