gpt4 book ai didi

javascript - 我如何有选择地在 Typescript 接口(interface)中嵌入一个或多个接口(interface)?

转载 作者:行者123 更新时间:2023-11-29 10:26:14 26 4
gpt4 key购买 nike

我想定义一个类型 D,它需要接口(interface) A 的所有字段,但也可以选择嵌入接口(interface) B 的字段,C 或两者兼而有之。

这是我试图定义它的方式:

interface A {
a1: number;
a2: number;
};

interface B {
b1: number;
b2: number;
};

interface C {
c1: number;
c2: number;
};

type D = A | (A & B) | (A & C) | (A & B & C);

let d: D;
d = {'a1': 1, 'a2': 2};
if ('c1' in d) {
d.c1 = 123;
}

但是, typescript 似乎不喜欢这样,并提示:属性“c1”在类型“从不”上不存在。

如果我对上面的解释不当,我希望类型 D 能够保存以下值:

{"a1": 1, "a2": 2}
{"a1": 1, "a2": 2, "b1": 3, "b2": 4}
{"a1": 1, "a2": 2, "c1": 5, "c2": 6}
{"a1": 1, "a2": 2, "b1": 3, "b2": 4, "c1": 5, "c2": 6}

但不是:

{"a1": 1} // missing field a2
{"a1": 1, "a2": 2, "b2": 4} // missing field b1
{"a1": 1, "a2": 2, "c1": 5} // missing field c2
{"a2": 2, "b1": 3, "c2": 6} // missing fields a1, b2, c1

我如何在 typescript 中做到这一点?

最佳答案

如果您注意到,如果您将鼠标悬停在下面第 3 行的 d 上,在第 2 行的赋值之后

let d: D;
d = {'a1': 1, 'a2': 2};
if ('c1' in d) { // mouse over `d` here
d.c1 = 123; // Property 'c1' does not exist on type 'never'.
}

typescript 巧妙地确定了 d 实际上是类型 A

但是如果你将它分配给返回 D 而不是子类型的东西,你将不会得到错误:

let d: D;
d = {'a1': 1, 'a2': 2} as D; // cast
if ('c1' in d) {
d.c1 = 123; // no error
}

function makeD(): D {
return { a1: 1, a2: 2 };
}

let d: D;
d = makeD();
if ('c1' in d) {
d.c1 = 123; // no error
}

换句话说,typecritp 的类型意识是这样的:

let d: D; // `d` is `D` (possibly unassigned)
d = {'a1': 1, 'a2': 2}; // `d` is assigned something that matches it's sub type `A`, so `d` is `A` after this
if ('c1' in d) { // 'c1' is not in `A` so `d` is never in side this if block
d.c1 = 123; // Property 'c1' does not exist on type 'never'.
}

所以你想把它改成:

let d: D; // `d` is `D` (possibly unassigned)
d = somthingThatIsD; // `d` is assigned (still `D`)
if ('c1' in d) { // 'c1' is in `D` so `d` is still `D`
d.c1 = 123; // no error
}

关于javascript - 我如何有选择地在 Typescript 接口(interface)中嵌入一个或多个接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58560657/

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