Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create type with two possible variants in Typescript

Tags:

typescript

Is there a way in Typescript to declare a variable which can be Int16Array or Uint16Array and nothing more?

like image 455
Alexey Nikiforov Avatar asked Mar 18 '26 20:03

Alexey Nikiforov


1 Answers

TypeScript 1.4 has support for Type Unions, the notation is:

var arr: Int16Array|Uint16Array;

Common methods that both of these have will be available on arr. If you use instanceof or typeof checks on arr in conditional/branched code, it will infer the type of arr in those branches.

TypeScript 1.4. also has support for type aliases:

type My16Array = Int16Array | Uint16Array;

You can then use:

var arr: My16Array;
like image 122
EyasSH Avatar answered Mar 21 '26 15:03

EyasSH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!