具有未知键但只有数值的对象的打字稿类型? [英] typescript type for object with unknown keys, but only numeric values?

查看:28
本文介绍了具有未知键但只有数值的对象的打字稿类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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} 

但它可能看起来像

{asdf: 1}

我希望打字稿编译器知道对于所有存在的键,值都是数字.我尝试了诸如 type numObj = {string: number}type numObj = {[string]: number} 之类的东西,但都不起作用.

I want the typescript compiler to know that for all present keys, the value is numeric. I tried things like type numObj = {string: number} and type numObj = {[string]: number} but neither works.

什么是适合的类型声明?

What is the suiting type declaration?

推荐答案

由 jonrsharpe 在他的评论中给出 具有未知键但只有数值的对象的打字稿类型?:

As given by jonrsharpe in his comment typescript type for object with unknown keys, but only numeric values?:

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

{ [key: string]: number }? Read the docs on indexable types: www.typescriptlang.org/docs/handbook/interfaces.html

这篇关于具有未知键但只有数值的对象的打字稿类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆