【问题标题】:typescript type for object with unknown keys, but only numeric values?具有未知键的对象的打字稿类型,但只有数值?
【发布时间】:2018-05-30 13:29:29
【问题描述】:

我有一个在运行时从外部源获取的对象。它具有任意字符串值的键,但只有数字值。它可能看起来像:

{foo:1, bar:3} 

但它也可能看起来像

{asdf: 1}

我希望 typescript 编译器知道 对于所有存在的键,值都是数字。我尝试了type numObj = {string: number}type numObj = {[string]: number} 之类的方法,但都不起作用。

什么是适合的类型声明?

【问题讨论】:

标签: typescript object types


【解决方案1】:

正如 jonrsharpe 在他的评论 typescript type for object with unknown keys, but only numeric values? 中给出的:

{ [key: string]: number }?阅读有关可索引类型的文档: www.typescriptlang.org/docs/handbook/interfaces.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2020-04-19
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多