简体   繁体   English

具有未知键但只有数值的对象的打字稿类型?

[英]typescript type for object with unknown keys, but only numeric values?

I have an object that I get from an external source at runtime.我有一个在运行时从外部来源获取的对象。 It has arbitrary string string valued keys, but only numric values.它具有任意字符串字符串值键,但只有数字值。 It could look like:它可能看起来像:

{foo:1, bar:3} 

but it might as well look like但它也可能看起来像

{asdf: 1}

I want the typescript compiler to know that for all present keys, the value is numeric .我希望打字稿编译器知道对于所有存在的键,其值为 numeric I tried things like type numObj = {string: number} and type numObj = {[string]: number} but neither works.我尝试了type numObj = {string: number}type numObj = {[string]: number}但都type numObj = {[string]: number}

What is the suiting type declaration?什么是适合类型声明?

As given by jonrsharpe in his comment typescript type for object with unknown keys, but only numeric values?正如 jonrsharpe 在他的注释 typescript type for object with unknown keys 中给出的那样,但只有数值? :

{ [key: string]: number }? { [键:字符串]:数字}? Read the docs on indexable types: www.typescriptlang.org/docs/handbook/interfaces.html阅读关于可索引类型的文档: www.typescriptlang.org/docs/handbook/interfaces.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM