Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I tried things like type numObj = {string: number} and type numObj = {[string]: number} but neither works.

What is the suiting type declaration?

like image 628
LudvigH Avatar asked Dec 16 '17 16:12

LudvigH


People also ask

How would you define type for object keys in TypeScript?

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings.

What is type unknown in TypeScript?

TypeScript 3.0 introduces a new top type unknown . unknown is the type-safe counterpart of any . Anything is assignable to unknown , but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing.

Is object a data type in TypeScript?

object is a type that represents the non-primitive type, i.e. anything that is not number , string , boolean , bigint , symbol , null , or undefined . Argument of type 'undefined' is not assignable to parameter of type 'object | null'.Argument of type 'undefined' is not assignable to parameter of type 'object | null'.

What is object literal in TypeScript?

When you create an object literal with {...} syntax, TypeScript will consider it to be a new object type, or type shape, based on its properties. That object type will have the same property names and primitive types as the object's values. Accessing properties of the value can be done with either value.


1 Answers

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

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

like image 175
LudvigH Avatar answered Sep 28 '22 19:09

LudvigH