2

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thanks for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.