user11931362
user11931362

Reputation:

How to determine type of variable in typescript, array of numbers or array of strings?

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 ?

Upvotes: 1

Views: 4065

Answers (4)

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)[] = [];

Upvotes: 2

Tomas Vancoillie
Tomas Vancoillie

Reputation: 3868

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

Upvotes: 2

Romi Halasz
Romi Halasz

Reputation: 2009

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

Upvotes: 0

Paul
Paul

Reputation: 498

@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>();

Upvotes: 1

Related Questions