当前位置: 首页 > 科技观察

一种设置TypeScript类型的更具可读性的方法

时间:2023-03-12 01:25:21 科技观察

TypeScript提供了一些内置的实用程序类型,以便更好地将类型从一种形式转换为另一种形式。这些内置类型是全局可用的,所以使用起来很方便。TypeScript泛型在了解TypeScript实用程序之前,类型、类型别名和泛型很重要。我们可以为TypeScript中的任何现有类型创建类型别名。typeMyString=string;lethelloWorldMessage:MyString='HelloWisdomGeek';泛型用于创建可重用的类型别名。假设我们有一个返回任何传递值的恒等函数:constidentity=(arg:string):string=>arg;如果我们想返回一个数字类型怎么办?有些朋友可能会使用any而不是特定的类型constidentity=(arg:any):any=>arg;但这减少了参数的类型信息,因此,也失去了TypeScript带来的好处。我们希望以一种可用于表示返回类型的方式捕获参数的类型。这就是泛型派上用场的地方。我们将使用适用于类型而不是值的类型变量。constidentity=(arg:T):T=>arg;接下来,在调用函数时指定函数的类型:constoutput=identity("HelloWisdomGeek");TypeScript中的内置实用程序类型这些工具类型在4.0版之前可用,无需任何附加包。PartialPritial使T的所有属性都是可选的。typeBlogPost={title:string;author:string;}typePartialBlogPost=Partial;/*等同于{title?:string;author?:string;}*/RequiredRequired使T的所有属性都必填。typePartialBlogPost={title?:string;author?:string;}typeBlogPost=Required;/*等同于{title:string;author:string;}*/ReadonlyReadonly将T的所有属性更改为只读。typeBlogPost={title:string;author:string;}typeBlogPost=Readonly;/*等同于{readonlytitle:string;readonlyauthor:string;}*/PickPick提取T中的属性,属性来fromK.typePoint3D={x:number,y:number,z:number,};typePoint2D=Pick;/*等价于{x:number,y:number}*/ParametersParametersT是Function,提取函数中的返回值是元组。typeT0=Parameters<()=>string>;//typeT0=[]typeT1=Parameters<(s:string)=>void>;//typeT1=[s:string]typeT2=Parameters<(arg:T)=>T>;//typeT2=[arg:unknown]OmitOmit与Pick相反(去除属性).typePoint3D={x:number,y:number,z:number,};typePoint2D=Omit;/*sameas{x:number,y:number}*/RecordRecord生成接口,属性都是K的属性,k的所有属性都有类型TtypeBlogPost=Record<'title'|'author',strnig>/*sameas{title:string;author:string;}*/Record版本的声明如果所有类型都具有相同的值则更加简洁和可读,因为它们都具有相同的类型。ExtractExtract-用于提取可以分配给类型U的类型T的成员typeT0=Extract<"a"|"b"|"c","a"|"f">;//typeT0="a"typeT1=Extractvoid),Function>;//typeT1=()=>voidExcludeExclude-用于从类型T中移除不属于类型U的成员.typeT0=Exclude<"a"|"b"|"c","a">;//typeT0="b"|"c"typeT1=Excludevoid),Function>;//typeT2=string|numberNonNullableNonNullable-用于从类型T中删除未定义和空类型。typeT0=NonNullable;//typeT0=string|numbertypeT1=NonNullable;//typeT1=string[]ReturnTypeReturnType-获取函数类型的返回类型typeT0=ReturnType<()=>string>;typeT0=stringtypeT1=ReturnType<(s:string)=>void>;typeT1=voidtypeT2=ReturnType<()=>T>;typeT2=unknowntypeT3=ReturnType<()=>T>;typeT3=number[]typeT5=ReturnType;typeT5=anytypeT6=ReturnType;typeT6=nevertypeT7=ReturnType;InstanceTypeInstanceType-获取构造函数实例类型classC{x=0;y=0;}typeT0=InstanceType;typeT0=CtypeT1=InstanceType;typeT1=anytypeT2=InstanceType;typeT2=never~完,我是小智。更多实用分类请自行查看官网。https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasetringtype作者:SARANSHKATARIA译者:前端小智来源:wisdomgeek原文:https://www.wisdomgeek.com/development/web-development/typescript/using-utility-types-for-transforming-typescript-types/本文转载自微信公众号“大千世界”,可通过以下二维码关注。转载本文请联系大千世界公众号。