当前位置: 首页 > Web前端 > HTML

打字稿学习笔记

时间:2023-03-28 18:03:35 HTML

1.Number,Boolean,Stringletnum:number=6;letstr:string="6";letbool:boolean=false;2.Array//ArrayletnumArr1:number[]=[4,3,9,9];//也可以使用泛型letnumArr2:Array=[7,1,3,5];3、元组元组可以进一步规范固定位置的类型,长度不可变;//tuppleletperson1:[number,string]=[17,"aYao"]4.联合类型//Unionletuni:string|数;uni=2;uni=“2”;5。Enum枚举//EnumenumColor{red,green,blue}letcolor=Color.blueconsole.log(color)//26.anyletrandomVal:any=666;randomVal="777";randomVal={};7.void,undefinedandneverfunctionprintResult():void{console.log("lalala~");}console.log(printResult())//undefined8.接口和类接口IPoint{x:number;y:数字;绘制点:()=>无效;getDistances:(p:IPoint)=>number;}//让drawPoint=(point:Point)=>{//console.log({x:point.x,y:point.y});//};//drawPoint({x:4,y:7});classPointimplementsIPoint{x:number;是:努琥珀色;//构造函数构造函数;?:表示可选参数,不可赋值constructor(x?:number,y?:number){this.x=x;这个.y=y;}drawPoint=()=>{console.log("x:"+this.x+",y:"+this.y);};getDistances=(p:IPoint)=>{returnMath.pow(p.x-this.x,2)+Math.pow(p.y-this.y,2);};}constpoint=newPoint(2,3);点.drawPoint();//x:2,y:39。泛型//传递输入的任何类型letlastInArr=(arr:Array):T=>{returnarr[arr.length-1];};constl1=lastInArr([1,2,3,4]);//numberconstl1=lastInArr([1,2,3,4]);//stringconstl2=lastInArr(["1","2","3","4"]);//number//指定类型constl3=lastInArr(["1","2","3","4"]);//数字|string//再比如ref函数,表面参数和返回类型都是stringconstcodeUrl=ref("")10.typetype表示类型别名typeN=numbertypeU=N|string//U表示数字或stringtypeletnum:U=5letstr:U='abc'letarr:U=[]//报错classclassGreeterin11.ts{//类似于java中的Stringnamename:string;构造函数(名称){this.name=名称;}greeting():string{returnthis.name;}}constgreeter=newGreeter('China')console.log(greeter.greeting())//中国