我想创建一个期望几乎每个键的值都相同的类型。但是,我还想要求某些键的值必须是不同的类型。
interface Item<T, U> {
[key: string]: T;
specificKey?: U;
}
这可以预料会出现错误:
Property 'specificKey' of type 'U' is not assignable to string index type 'T'.
我的第一个想法是尝试使用“排除”:
interface Item<T, U> {
[key: Exclude<string, 'specificKey'>]: T;
specificKey?: U;
}
但是,这也会产生错误:
An index signature parameter type cannot be a type alias.
是否可以设置[key: string]
应用于除specificKey
以外的所有字符串?
答案 0 :(得分:1)
这是TS中的限制。有关详细信息,请参见this link。当前,无法正确指定所需的类型。最接近的是使用交叉点类型:
type Item<T, U> = { [k: string]: T } & { specificKey: U }
但是这种解决方法仅适用于“读取”方面:
let item: Item<boolean, number>
// to read, it's fine
const bool = item['foobar'] // good
const num = item.specificKey // good
它仍然在“写”侧中断:
// to write, TS raises same incompatible error
let item: Item<boolean, number> = { specificKey: 1, foobar: true }
// ~~~~~ <-- Property 'specificKey' is incompatible with index signature.
// Type 'number' is not assignable to type 'boolean'.
// you have to mute it with `as any`
let item: Item<boolean, number> = { specificKey: 1, foobar: true } as any