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

TypeScript高级类型总结(附代码示例)

时间:2023-03-14 20:16:21 科技观察

TypeScript是一种类型化语言,允许您指定变量、函数参数、返回值和对象属性的类型。下面是如何使用TypeScript的高级类型的摘要,并附有示例。Intersection类型Intersection类型是一种组合多种类型的方式。这意味着您可以组合多个给定类型并获得具有所有属性的新类型。typeLeftType={id:numberleft:string}typeRightType={id:numberright:string}typeIntersectionType=LeftType&RightTypefunctionshowType(args:IntersectionType){console.log(args)}showType({id:1,left:"test",right:"test"})//Output:{id:1,left:"test",right:"test"}代码中的IntersectionType”结合了两种类型:LeftType和RightType,使用&符号构造交集类型。联合类型联合类型用于在给定的变量中使用不同类型的注解。typeUnionType=string|numberfunctionshowType(arg:UnionType){console.log(arg)}showType("test")//Output:testshowType(7)//Output:7showType函数是一个联合类型,可以接受字符串和数字作为参数。functionshowType(args:T){console.log(args)}showType("test")//Output:"test"showType(1)//Output:1构造一个泛型类型,需要使用指针括号并将T作为参数传递。在下面的代码中,我使用名称T(名称由您决定),然后使用不同的类型注释调用showType函数两次,因为它是可重用的。interfaceGenericType{id:numbername:T}functionshowType(args:GenericType){console.log(args)}showType({id:1,name:"test"})//输出:{id:1,name:"test"}functionshowTypeTwo(args:GenericType){console.log(args)}showTypeTwo({id:1,name:4})//输出:{id:1,name:4}还有一个例子,有一个接口GenericType接受泛型类型T。由于它是可重用的,我们可以用字符串和数字来调用它。interfaceGenericType{id:Tname:U}functionshowType(args:GenericType){console.log(args)}showType({id:1,name:"test"})//输出:{id:1,name:"test"}functionshowTypeTwo(args:GenericType){console.log(args)}showTypeTwo({id:"001",name:["This","is","a","Test"]})//Output:{id:"001",name:Array["This","is","a","Test"]}泛型可以接收多个参数。示例中传入了两个参数:T和U,然后用作属性的类型注释。也就是说,我们现在可以给这个接口,并提供两种不同的类型作为参数。实用程序TypeScript提供了方便的内置实用程序,可帮助我们轻松操作类型。使用时需要将要处理的类型传递给<>。(1)PartialPartialPartial允许您将类型T的所有属性设为可选。它会添加一个?在每个字段旁边标记。interfacePartialType{id:numberfirstName:stringlastName:string}functionshowType(args:Partial){console.log(args)}showType({id:1})//输出:{id:1}showType({firstName:"John",lastName:"Doe"})//Output:{firstName:"John",lastName:"Doe"}代码中有一个接口叫做PartialType,作为函数参数的类型注解显示类型()。要使属性可选,必须使用Partial关键字并且必须将PartialType类型作为参数传递。所有字段现在都是可选的。(2)RequiredRequired与Partial不同,Required使得类型T的所有属性都是强制的。interfaceRequiredType{id:numberfirstName?:stringlastName?:string}functionshowType(args:Required){console.log(args)}showType({id:1,firstName:"John",lastName:"Doe"})//Output:{id:1,firstName:"John",lastName:"Doe"}showType({id:1})//Error:Type'{id:number:}'缺少类型中的以下属性'Required':firstName,lastName使所有符合条件的属性成为必需属性,即使它们以前是可选的。如果省略该属性,TypeScript将引发错误。(3)ReadonlyReadonly该类型会转换类型T的所有属性,使它们不能被重新赋值。interfaceReadonlyType{id:numbername:string}functionshowType(args:Readonly){args.id=4console.log(args)}showType({id:1,name:"Doe"})//错误:无法给出'id'因为它是一个只读属性。在代码中使用Readonly使ReadonlyType的属性不可重新分配。如果您必须为这些字段赋值,则会引发错误。除此之外,您还可以在属性前使用关键字readonly使其不可重新分配。interfaceReadonlyType{readonlyid:numbername:string}(4)PickPick它允许您通过选择类型的属性k从现有模型T创建新类型。interfacePickType{id:numberfirstName:stringlastName:string}functionshowType(args:Pick){console.log(args)}showType({firstName:"John",lastName:"Doe"})//输出:{firstName:"John"}showType({id:3})//错误:Objectliteralmayoonlyspecifyknownproperties,and'id'doesnotexistintype'Pick'Pick是一样的和之前看到的有点不一样。它有两个参数——T是要选择的元素类型,k是要选择的属性。您还可以通过使用通用竖线符号(|)分隔多个字段来选择它们。(5)OmitOmitOmit与Pick相反。它从类型T中删除了K属性。interfacePickType{id:numberfirstName:stringlastName:string}functionshowType(args:Omit){console.log(args)}showType({id:7})//输出:{id:7}showType({firstName:"John"})//Error:Objectliteralmayonlyspecifyknownproperties,and'firstName'doesnotexistintype'Pick'省略与Pick类似。(6)ExtractExtractExtract允许您通过选择出现在两个不同类型中的属性来构造一个类型。它从T中提取所有可分配给U的属性。interfaceFirstType{id:numberfirstName:stringlastName:string}interfaceSecondType{id:numberaddress:stringcity:string}typeExtractExtractType=Extract//输出:“id”在代码中的两个接口中有一个共同的属性id。id可以通过Extract来提取。如果您有多个共享字段,Extract将提取所有相似的属性。(7)Exclude与Extract的不同之处在于Exclude通过排除两个不同类型中已经存在的属性来构造一个类型。它排除了所有可以分配给U的字段。"firstName"|"lastName"在上面的代码中,属性firstName和lastName可以分配给SecondType类型,因为它们在那里不存在。这些字段按预期由Extract返回。(8)RecordRecordRecord可以帮助您构造一个类型,该类型具有给定类型T的一组属性K。在将一种类型的属性映射到另一种类型时,使用Record非常方便。interfaceEmployeeType{id:numberfullname:stringrole:string}letemployees:Record={0:{id:1,fullname:"JohnDoe",role:"Designer"},1:{id:2,fullname:"IbrahimaFall",role:"Developer"},2:{id:3,fullname:"SaraDuckson",role:"Developer"},}//0:{id:1,fullname:"JohnDoe",role:"设计师"},//1:{id:2,fullname:"IbrahimaFall",role:"Developer"},//2:{id:3,fullname:"SaraDuckson",role:"Developer"}Record的工作原理简单的。在代码中,它需要数字作为类型,这就是我们将0、1和2作为employees变量的键的原因。如果尝试将字符串用作属性,则会引发错误。接下来,属性集由EmployeeType给出,因此该对象具有字段id、fullName和role。(9)NonNullableNonNullable允许您从类型T中删除null和undefined。typeNonNullableType=string|number|null|undefinedfunctionshowType(args:NonNullable){console.log(args)}showType("test")//输出:"test"showType(1)//输出:1showType(null)//Error:Argumentoftype'null'isnotassignabletoparameteroftype'string|number'.showType(undefined)//Error:Argumentoftype'undefined'isnotassignabletoparameteroftype'string|number'.代码中,将NonNullableType作为参数传递给NonNullable,NonNullable从这个Type中传递排除null和undefined构造新的类型。也就是说,如果你传递一个可为null的值,TypeScript将抛出一个错误。顺便说一句,如果您将--strictNullChecks标志添加到您的tsconfig文件,TypeScript将应用非空检查规则。映射类型映射类型允许您采用现有模型并将其每个属性转换为新类型。请注意,前面描述的一些实用程序类型也是映射类型。typeStringMap={[PinkeyofT]:string}functionshowType(arg:StringMap<{id:number;name:string}>){console.log(arg)}showType({id:1,name:"测试"})//错误:Type'number'isnotassignabletotype'string'.showType({id:"testId",name:"ThisaTest"})//输出:{id:"testId",name:"ThisisaTest"}StringMap<>会将传入的任何类型转换为字符串。也就是说如果在函数showType()中使用,接收到的参数必须是字符串,否则TypeScript会报错。类型保护类型保护允许您使用运算符来检查变量或对象的类型。它实际上是一个条件块,用于检查typeof、instanceof或in返回的类型。(1)typeofffunctionshowType(x:number|string){if(typeofx==="number"){return`Theresultis${x+x}`}thrownewError(`Thisoperationcan'tbedoneona${typeofx}`)}showType("I'mnotanumber")//Error:Thisoperationcan'tbedoneonastringshowType(7)//Output:Theresultis14代码中有正常的JavaScript条件块检查typeof检测到的参数类型。在这种情况下,您的类型受到保护。(2)instanceofclassFoo{bar(){return"HelloWorld"}}classBar{baz="123"}functionshowType(arg:Foo|Bar){if(arginstanceofFoo){console.log(arg.bar())returnarg.bar()}thrownewError("Thetypeisnotsupported")}showType(newFoo())//Output:HelloWorldshowType(newBar())//Error:Thetypeisnotsupported和前面的例子一样,这也是一个类型保护,检查接收到的参数是不是Foo类的一部分并处理它。(3)ininterfaceFirstType{x:number}interfaceSecondType{y:string}functionshowType(arg:FirstType|SecondType){if("x"inarg){console.log(`Theproperty${arg.x}exists`)return`Theproperty${arg.x}exists`}thrownewError("Thistypeisnotexpected")}showType({x:7})//Output:Theproperty7existsshowType({y:"ccc"})//Error:Thistypeisnotexpectedincode,inoperator用于检查对象上是否存在属性x。Conditional类型用于测试两种类型,并根据测试结果选择其中一种。此示例中的typeNonNullable=Textendsnull|undefined?never:TNonNullable检查类型是否为null并相应地处理它。