gpt4 book ai didi

javascript - TypeScript:一个接口(interface)属性需要另一个属性为真

转载 作者:行者123 更新时间:2023-12-03 06:58:04 24 4
gpt4 key购买 nike

如何定义键:a, b, c, bar作为未定义/空/可选输入如果 foo 是假的 ?换句话说,我需要这些属性是 必填 仅当 foo 是真的 .

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?
}

关于javascript - TypeScript:一个接口(interface)属性需要另一个属性为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64933861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com