Categories
TypeScript Answers

How to cast arrays with TypeScript?

Spread the love

Sometimes, we want to cast arrays with TypeScript.

In this article, we’ll look at how to cast arrays with TypeScript.

How to cast arrays with TypeScript?

To cast arrays with TypeScript, we can use the as keyword or add the variable name before the array expression.

For instance, we write

const a = x as number[];

or

const a = x as Array<number>;

to cast x to a number array with as.

Also, we can write

const a = <number[]>x;

or

const a = <Array<number>>x;

to cast x to a number array by putting the type in brackets before x.

Conclusion

To cast arrays with TypeScript, we can use the as keyword or add the variable name before the array expression.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *