javascriptarraystypescriptobjectecmascript-6

Object.keys using numbers in typescript


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?


Solution

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