Object.keys using numbers in typescript

12,335

Solution 1

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 };

Solution 2

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

Solution 3

Why does Typescript assume string[]? And what is the correct way of creating an array of numbers here?

Because object property names are always strings (or, to properly explain that, are always coerced to strings), hence the default signature assumes a string[] as default type, as the intellisense even suggests:

enter image description here

Besides, you can't ensure that, at runtime, those keys will be numbers. Defining a type that strictly defines that object to have numeric keys has no effect at runtime, hence it's always safer to safely cast the values to the desired type:

const sizes: number[] = Object.keys(foo).map(Number); // beware of possible NaN here.
Share:
12,335

Related videos on Youtube

David Hellsing
Author by

David Hellsing

Pushing binaries at Aino.

Updated on September 15, 2022

Comments

  • David Hellsing
    David Hellsing over 1 year
    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?