在使用枚举作为对象键时,我遇到了 TS 的一些奇怪行为。
我期望 TS 错误,但事实并非如此,我不明白为什么。
enum List {
sm = "sm",
md = "md",
}
export interface Dictionary<T = any> {
[index: string]: T;
}
export type OptionalDictionary<T, K extends string = string> = { [P in K]?: T };
type MessageType = Dictionary<string | null>;
type MessagesType = OptionalDictionary<MessageType, List>;
type Values = { receiver: List; text: string };
const values = { receiver: List.sm, text: "123" };
const { receiver, text } = values;
const data: MessagesType = {
// [receiver]: { text }, // correct
[receiver]: text // wrong, but no error
};
const data2: MessagesType = {};
// data2[receiver] = { text }; // correct
data2[receiver] = text; // wrong, had error
console.log(data[receiver] === data2[receiver]); // true
Sandbox
这看起来像是 TypeScript 中一些不幸行为的相互作用。
首先,联合类型的计算键一直扩展到string
索引,就像主题一样微软/TypeScript#13948,一个长期存在的错误/限制。所以类型{[receiver]: text}
被视为{[k: string]: string}
而不是类似的东西{sm: string} | {md: string}
。我不确定何时或是否会改变,但这就是正在发生的事情。
其次,索引签名(例如{[k: string]: string}
始终被认为可分配给弱类型(具有所有可选属性的类型,例如{sm?: {text: string}, md?: {text: string}}
),即使索引签名的属性类型与弱类型的属性类型不兼容!这是主题微软/TypeScript#27144,也被认为是一个错误。同样,不知道何时或是否会解决这个问题;它被列为“未来”。
这两个错误放在一起给你带来了你所看到的行为:你可以分配{[receiver]: text}
到一个类型的变量MessagesType
没有错误。这就是解释;不知道你应该做什么,除了可能去这两个 GitHub 并给他们一个?????
无论如何,希望有帮助;祝你好运!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)