interface A {
name: string;
age: number;
}
type B = A | Record<keyof A, null>;
在第一个键的值之后,ts 确定正在使用哪个接口,这是合乎逻辑的,但是我们如何才能使混合版本也工作呢?
const obj: B = {
age: null,
name: 'some'
}
Type 'string' is not assignable to type 'null'
interface A {
name: string;
age: number;
}
type B = A | Record<keyof A, null>;
在第一个键的值之后,ts 确定正在使用哪个接口,这是合乎逻辑的,但是我们如何才能使混合版本也工作呢?
const obj: B = {
age: null,
name: 'some'
}
Type 'string' is not assignable to type 'null'
据我了解,您想要添加分配给每个属性的
interface A能力。type Bnull在您的代码中,您使用Record,之后 y
B是类型interface A或type B如果你打开它,它看起来是这样的Record:也就是说,您的类型
B要么是 type 的对象,要么是所有属性都必须是 type 的A对象。在你的例子中,你把事情搞混了。是的,你写过这个,我只是解释了一下。Anull所以,你可以尝试这样做:
这样我们就可以将每个属性设置为
null。PS我可能会非常愚蠢地解释它并且在单词中感到困惑,我
typescript还不是很熟悉它,但我希望我或多或少地解释了它。