Is there any way to trigger a typescript compiler error in the code

I would like to check if an array has a specific length. If the array length exceeds the limit, I would like to raise an error (or warning) when running the compiler.

Is this possible?

Upvotes: 2

Views: 121

Answers (1)

Kewin Dousse
Kewin Dousse

Reputation: 4027

TypeScript has what's called Tuples, which are essentially fixed-length arrays. You can't specify the length programmatically, but if your max length is low enough, what you can do is use union types (symbol |) to add together tuples of different lengths, until your wanted maximum.

Here's an example of how you could do it :

type maxThree = [] | [any] | [any, any] | [any, any, any]; // Any array of three or less elements

let arrayOk: maxThree = [1];
let arrayStillOk: maxThree = [1, 2];
let arrayTooLong: maxThree = [1, 2, 3, 4]; // <- Compilation error

Playground Link

Edit : After some research, it is possible to define a Tuple's length programmatically, although it's quite hacky and not completely type-safe. Still, this might interest you : https://stackoverflow.com/a/52490977/1841827

Upvotes: 1

Related Questions