admin管理员组文章数量:1356135
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 badges1 Answer
Reset to default 10I 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?
}
本文标签: javascriptTypeScript an interface property requires another property to be trueStack Overflow
版权声明:本文标题:javascript - TypeScript: an interface property requires another property to be true - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744043297a2581064.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论