type Foo = { [key: number]: string }
const foo: Foo = { 100: 'foo', 200: 'bar' }
const sizes: number[] = Object.keys(foo)
Gives me:
Type 'string[]' is not assignable to type 'number[]
Why does Typescript assume string[]
? And what is the correct way of creating an array of numbers here?
Object Keys in JavaScriptEach key in your JavaScript object must be a string, symbol, or number.
TypeScript like JavaScript supports numeric values as Number objects. A number object converts numeric literal to an instance of the number class. The Number class acts as a wrapper and enables manipulation of numeric literals as they were objects.
JavaScript number object follows IEEE standard to represent the floating-point numbers. By the help of Number() constructor, you can create number object in JavaScript. For example: var n=new Number(value);
All keys are strings in JavaScript - just use map
:
const sizes: number[] = Object.keys(foo).map(Number);
This'll only work for numeric strings - if it's a European string involving decimals, for instance, it'll be NaN
, and that never ends well.
console.log(Number("10,7"));
Or change either of your types:
const sizes: string[] = Object.keys(foo);
Or:
type Foo = { [key: string]: string };
Object properties names are always string, if you want to convert property names to numbers on the fly, you can use map(Number)
:
const sizes: number[] = Object.keys(foo).map(Number);
Pay attention because, if your property name can't be converter to number, you'll get NaN
in your sizes array
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