首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Typescript:从带有索引签名的对象中获取密钥

Typescript:从带有索引签名的对象中获取密钥
EN

Stack Overflow用户
提问于 2019-05-30 03:23:56
回答 1查看 435关注 0票数 0

我正在从TypeScript模块导入以下类型和函数:

代码语言:javascript
复制
type Attributes = {
  [key: string]: number;
};

function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any {
  // ...
}

我无法修改上面的代码。

然后,我在自己的模块中实现了以下代码:

代码语言:javascript
复制
// 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,值是数字。所以我修改了我的代码:

代码语言:javascript
复制
// 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>({行上得到以下错误:

代码语言:javascript
复制
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作为类型参数传递

我可以接受第一个变种,但我不明白为什么第二个变种不能工作。有什么想法吗?

非常感谢

EN

回答 1

Stack Overflow用户

发布于 2019-05-30 03:35:10

如何确保"foo“| "bar”| "baz“类型作为类型参数传递,而不是string | number?

可以通过为attributes引入泛型类型参数来实现这一点

代码语言:javascript
复制
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将能够自己推断类型,因此您甚至不需要TypeKeys

Playground

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56367250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档