类型声明常用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 let isDone : boolean = false ; let name : string = "bob" ;let decLiteral : number = 6 ;let list : number [] = [1 , 2 , 3 ];let list : Array <number > = [1 , 2 , 3 ];let ro : ReadonlyArray <number > = a; let x : [string , number ]; enum Color {Red , Green , Blue }let notSure : any = 4 ;function warnUser ( ): void { console .log ("This is my warning message" ); } let unusable : void = undefined ; let u : undefined = undefined ; let n : null = null ;function error (message: string ): never { throw new Error (message); } declare function create (o: object | null ): void ;create ({ prop : 0 }); create (null ); function f ([first, second]: [number , number ] ) { console .log (first); console .log (second); } let {a, b}: {a : string , b : number } = o;type C = { a : string , b?: number }function f ({ a, b }: C ): void { }
类型断言 类型断言就是能够绕开ts的类型警告,类似一种强制执行
1 2 let someValue : any = "this is a string" ;let strLength : number = (<string >someValue).length ;
1 2 let someValue : any = "this is a string" ;let strLength : number = (someValue as string ).length ;
接口interface 对象和索引类型 1 2 3 4 5 6 7 8 9 10 11 interface SquareConfig { color?: string ; readonly x : number ; [propName : string ]: any ; } interface StringArray { readonly [index : number ]: string ; }
数组 1 2 3 4 5 6 interface StringArray { [index : number ]: string ; } let myArray : StringArray ;myArray = ["Bob" , "Fred" ];
函数 1 2 3 4 5 6 7 8 interface searchFn{ (a :number ,b :string ):boolean } let mySearch : searchFnmySearch=function (apple:number ,good:string ) { return true }
类 1 2 3 4 5 6 7 8 9 10 11 interface ClockInterface { currentTime : Date ; setTime (d : Date ); } class Clock implements ClockInterface { currentTime : Date ; setTime (d: Date ) { this .currentTime = d; } constructor (h: number , m: number ) { } }
继承接口 1 2 3 4 5 6 7 8 9 interface Shape { color : string ; } interface PenStroke { penWidth : number ; } interface Square extends Shape , PenStroke { sideLength : number ; }
绕过接口检查的三种方式 1.使用类型断言 2.将对象传递给一个新变量,用这个变量进行传参 3.字符串索引签名,[propName:string]:any
ts本地测试
1 2 3 1.全局安装ts 2.tsc --init 初始化ts配置 3.vscode终端 运行任务 tsc
箭头函数的类型添加
1 2 3 4 5 6 let getName :(x:number,y:number )=> number = function (x:number,y:number ):string{return x+y}var myAdd = function (x, y ) { return x + y + y + "" ; };