Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 222
David Hellsing Avatar asked Jun 28 '19 09:06

David Hellsing


People also ask

Can object keys be numbers?

Object Keys in JavaScriptEach key in your JavaScript object must be a string, symbol, or number.

Is number an object in TypeScript?

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.

How do you use numbers in 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);


2 Answers

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 };
like image 116
Jack Bashford Avatar answered Sep 21 '22 21:09

Jack Bashford


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

like image 36
Cristian Traìna Avatar answered Sep 21 '22 21:09

Cristian Traìna