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?
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.
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.
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'.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With