我正在从TypeScript模块导入以下类型和函数:
type Attributes = {
[key: string]: number;
};
function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any {
// ...
}
我无法修改上面的代码。
然后,我在自己的模块中实现了以下代码:
// variant 1
const attributes = { // this object is hard coded (not dynamically generated)
foo: 1,
bar: 2,
baz: 3
};
type Type = typeof attributes;
type Keys = keyof Type;
Fn<Keys>({
attributes
});
一切都运行得很完美。现在,我想将类型Attributes
类型赋给常量attribute
,因为我想确保键是string,值是数字。所以我修改了我的代码:
// variant 2
const attributes: Attributes = {
foo: 1,
bar: 2,
baz: 3
};
type Type = typeof attributes;// equals {[key: string]: number;}
type Keys = keyof Type;// equals string | number. Why ?
Fn<Keys>({// Here, I would like Keys to be "foo" | "bar" | "baz", instead I have string | number
attributes
});
我在Fn<Keys>({
行上得到以下错误:
Type 'string | number' does not satisfy the constraint 'string'.
Type 'number' is not assignable to type 'string'.ts(2344)
我不明白当索引签名明确指定键是字符串时,为什么类型Keys
等于string | number
?
如何确保将"foo" | "bar" | "baz"
类型而不是string | number
作为类型参数传递
我可以接受第一个变种,但我不明白为什么第二个变种不能工作。有什么想法吗?
非常感谢
发布于 2019-05-30 03:35:10
如何确保"foo“| "bar”| "baz“类型作为类型参数传递,而不是string | number?
可以通过为attributes
引入泛型类型参数来实现这一点
type Attributes = {
[key: string]: number;
};
function Fn<KeysOfAttributes extends keyof T, T extends Attributes>(opts: { attributes: T }): any {
// ...
}
const attributes = {
foo: 1,
bar: 2,
baz: 3,
};
Fn({
attributes
});
Typescript将能够自己推断类型,因此您甚至不需要Type
和Keys
https://stackoverflow.com/questions/56367250
复制相似问题