首页 > 其他分享 >Typescript类型题材 - NumberRange

Typescript类型题材 - NumberRange

时间:2022-12-04 20:00:51浏览次数:81  
标签:Typescript CArr NumberRange length extends 题材 type

题目

中文

有时我们需要限制数字的范围...

示例:

type result = NumberRange<2 , 9> //  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 

English

Sometimes we want to limit the range of numbers...
For examples.

type result = NumberRange<2 , 9> //  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 

答案

type NumberRange<
  L extends number,
  H extends number,
  CArr extends any[] = [],
  OArr extends unknown[] = [unknown],
  R extends number = H
> = H extends CArr['length']
  ? R
  : L extends CArr['length']
  ? NumberRange<OArr['length'], H, [any, ...CArr], [unknown, ...OArr], L | R>
  : NumberRange<L, H, [...CArr, any], [unknown, ...OArr]>;

在线演示

知识点

  • 使用元组的 length 进行计数
  • 将结果保存到泛型参数 R 内, 避免递归层数过多导致 H 超过 50 tsc报 possible infinity loop

标签:Typescript,CArr,NumberRange,length,extends,题材,type
From: https://www.cnblogs.com/laggage/p/type-challenge-number-range.html

相关文章

  • Typescript类型题材 - ConstructTuple
    题目中文构造一个给定长度的元组。例如typeresult=ConstructTuple<2>//期望得到[unknown,unkonwn]EnglishConstructatuplewithagivenlength.Forexam......
  • TypeScript中使用NodeJs日期格式化库myjs-common
    依赖包安装#安装myjs-common包[email protected]格式器表达式YEAR_FORMAT:年格式化-yyyyMONTH_FORMAT:月格式化-yyyy-MMDATE_FORMAT:日期格式化-yyyy-MM-ddH......
  • [Typescript] 125. Extreme - Object Key Paths
    Getallpossiblepathsthatcouldbecalledby _.get (alodashfunction)togetthevalueofanobjecttypeT1=ObjectKeyPaths<{name:string;age:number......
  • TypeScript 常见方法
    TypeScriptArray(数组)数组对象是使用单独的变量名来存储一系列的值。数组非常常用。假如你有一组数据(例如:网站名字),存在单独变量如下所示varsite1="Google";varsite2......
  • typescript学习总结
    typescript学习总结qq学习讨论群:910316886<!--安装:npmi-gtypescripttsc-v(查看typescript版本)将ts编译为js,在终端输入命令,tschello.ts执......
  • [Typescript] 124. Binary to Decimal
    Implement BinaryToDecimal<S> whichtakesanexactstringtype S consisting0and1andreturnsanexactnumbertypecorrespondingwith S when S isrega......
  • TypeScript
    报错函数实现重复法一:export{};//第一行增加这个语句是为了使文件里的变量不污染全局法二:在项目根目录运行:tsc--init之后根目录会生成一个json文件,文件名为:tscon......
  • [Typescript 4.9] Satisfies operator
    typeRGB=[number,number,number]constpalette:Record<'red'|'blue'|'green',string|RGB>={red:[255,0,0],green:"#00ff00",blue:[0,0,255......
  • [Typescript 4.9] Auto-Accessors in Classes
    Typescript4.9supportsanupcomingfeature:Auto-accessors:classPerson{accessorname:stringconstructor(name:string){this.name=name}} ......
  • [Typescript 4.9] 'in' operator
    Beforeversion4.9,youwillgettypeerrorforthecode:interfaceContext{packageJSON:unknown}functiontryGetPackageName(context:Context){const......