2

case 1

 type ArrayEqualLength<T,?> = [T]
 const a: ArrayEqualLength<number,1> = [1,1] // x
 const a: ArrayEqualLength<number,1> = [1] // o
 const a: ArrayEqualLength<number,2> = [1,1] // o

case 2 GreaterThan

 type ArrayGreaterThanLength<T,?> = [T]
 const a: ArrayGreaterThanLength<number,2> = [1,1] // x
 const a: ArrayGreaterThanLength<number,2> = [1] // x
 const a: ArrayGreaterThanLength<number,2> = [1,1,1] // o

I want to check array length in typescript!

I can't find it when I search. Help me. Thanks.

2 Answers 2

2

This might help with your first case: https://stackoverflow.com/a/52490977/12414867

For example:

type TupleEq<TItem, TLength extends number> = [TItem, ...TItem[]] & { length: TLength };
const a: TupleEq<number, 4> = [1, 2, 3, 4];

As for the second case, I'm not sure if it's possible in TS :/

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

Comments

-1

use Object no Array

Exmaple:

type ARRAY<T,?> = {
    array:Array<T>
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.