typeScript学习总结
一、 基础类型(12个)
-
布尔值(boolean)
let a:boolean = true;
-
数字(number)
支持十进制、十六进制(0x)、八进制(0o)、二进制(0b)let b:number = 1;
-
字符串(string)
let c:string = 'string';
-
数组(number[]、string[] … or Array[number] …)
let d:number[] = [1,2,3,4];
-
元祖([number,string,…])
元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同let e:[number,string] = [123,'456'];
-
枚举(enum)
enum Color {Red, Green, Blue} let f: Color = Color.Green;//f=2; let g:string = Color[2];//g='Green'
-
任意(any)
let h:any = 1; let i:any = '1';
-
空(void)
function warnUser(): void { console.log("This is my warning message"); }
-
null(null)
let j:null = null;
-
undefinded(undefinded)
let k:undefinded = undefinded;
-
不存在(never)
never类型表示的是那些永不存在的值的类型(抛出异常、函数表达式、箭头函数表达式返回类型)// 返回never的函数必须存在无法达到的终点 function error(message: string): never { throw new Error(message); }
-
对象(object)
存放对象类型let obj:object = {obj:'obj'};
二、接口(interface)
通常用于函数入参对象中属性的定义
-
基本使用
//基础函数 function print(props){ //这时无法知道 props 的属性 充满不确定性 return `<div style="color:${props.color}" >${props.msg}</div>`; } //定义接口 interface PrintProps { msg:string,//必传参数 color?:string,//可选参数 readonly id?:number,//只读属性 和 const 比较 如果是变量用const 参数用readonly } function print(prop:PrintProps ){ //这样 在使用函数时 要符合接口规则 才能通过语法检查 return `<div style="color:${props.color}" >${props.msg}</div>`; } print({msg:'msg'});//正确 参数多传,少传都不行 print({msg:'msg',msgeee:'msg'});//错误 print({msgeee:'msg'});//错误
2.类型断言(as | <>) 和 字符串索引签(可索引类型)
如果想要绕开检查,传入一个符合条件但拥有额外属性的参数//按理 必选参数填入后 应该可以成功了 结果不通过语法检查 print({msg:'msg',msgeee:'msg'});//错误 //(1)使用类型断言 成功通过语法检查 print({ msg : 'msg' , msgeee : ' msg ' } as PrintProps );//正确 //(2)最佳的方式是能够添加一个字符串索引签名(这个对象可能具有某些做为特殊用途使用的额外属性) // 字符串索引签名第二个作用:会让接口变成可索引的类型,例如 PrintProps['msg'] interface PrintProps { msg:string,//必传参数 color?:string,//可选参数 readonly id?:number,//只读属性 和 const 比较 如果是变量用const 参数用readonly [propName: string]: any }
3.接口关系(implements)
//实现 interface ClockInterface { currentTime: Date;//属性方法 setTime(d: Date); } class Clock implements ClockInterface { currentTime: Date; setTime(d: Date) { this.currentTime = d; } constructor(h: number, m: number) { } }
//继承 可多继承 用逗号分隔 interface Shape { color: string; } interface Square extends Shape { sideLength: number; } let square = <Square>{}; square.color = "blue"; square.sideLength = 10;