Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

arrays - 如何在打字稿中检查数组长度(How to check array length in typescript)

case 1

(情况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

(案例2大于)

 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.

(谢谢。)

  ask by bugtype kr translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(这可能对您的第一种情况有所帮助: 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 :/

(至于第二种情况,我不确定在TS中是否可行:/)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...