1

I have a variable like

const data = [];

In some places in my App, data looks like string array or number array

// data [1, 2, 3]
// data ["1", "2", "3"]

How can I get the type of this variable - type string array or number array ?

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23
  • Is it possible to have both numbers and strings in an array ? – Romi Halasz Dec 17 '19 at 07:39
  • It seems like you have *different* data in it at different points. Settle on just one - whatever makes sense for your use-case, then give the variable *that* type and then ensure you only have one type going into it. For example, if you declare it to be `number[]` then convert all input to numeric before adding into the array. – VLAZ Dec 17 '19 at 07:39
  • @RomiHalasz Yes, no real problem with that `["hello", 42, true]` is valid. – VLAZ Dec 17 '19 at 07:40
  • @RomiHalasz No only number or only string. –  Dec 17 '19 at 07:42
  • @0xD34F _Array of numbers or array of strings_ - `string[] | number[]` – Aleksey L. Dec 17 '19 at 08:16

4 Answers4

2

Yes you can type your variables with a single type

// type data as an array of strings
const data: string[] = [];

// type data as an array of numbers
const data: number[] = [];

// type data as an array of objects
const data: object[] = [];

If you want to use a mix of types in your array, you can type it as any. But this may not be a good practise.

const data: any[] = [];

For more information about type in typescript, look here: Basic type documentation

For defining array with multiple types, look here: https://stackoverflow.com/a/29382420/1934484

Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45
2

You can define your array like this the typescript compiler will only allow strings

const array: Array<string> = [];

or if you want to have strings and numbers define it like this

const array: Array<string | number> = [];

You can also define it this way

const array: string[] = [];
const array: (string | number)[] = [];
kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25
1

@Tomas Vancoillie has the right idea.

You can declare them with the : operator.

You can also infer the type with Array(), for example:

let myStringArray = Array<string>();
Paul
  • 478
  • 2
  • 16
0

If you only need to get the type of the elements in the, since they are either string or number, you can just get the type of the first element, since all other elements have the same type:

typeof data[0] // string or number

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23