// 布尔值let isDone: boolean =false// 数字let decLiteral: number =6// 字符串let name2: string ="bob"// 数组let list: number[]=[1,2,3]let list2: Array<String>=['1','2','3']// 元组let x:[string, number]=['hello',10]// 枚举 经测试:里面的值暂只能是number和string类型、若是为number类型,例如Blue=3,则可通过:string = Color[3]获取枚举名enum Color { Red ='1', Green ='2', Blue =3, yellow =4, pink ='5'}let c: Color = Color.Green
let colorName: string = Color[3]// Any 动态类型let notSure: any =4
notSure ="maybe a string instead"
notSure =false// 使用数组时,元素是不同类型的
notSure =[1,2,'3',{ a:1}]// VoidfunctionwarnUser():void{
console.log("This is my warning message")}// Null 和 Undefinedlet u1: number = undefined
let n1: number =null// Never// 返回never的函数必须存在无法达到的终点、后续代码不执行(例如error、死循环等)functionerror(message: string): never {thrownewError(message)}functionfail(){returnerror("Something failed")}functioninfiniteLoop(): never {while(true){}}// 对象let o: object ={ a:1, b:2, c:3, d:[{ da:1},2], e:{ ea:1, eb:2}}
函数
// 函数functionadd(x: number, y?: number): number {return x + y
}letmyAdd=function(x: string ='3',...y: string[]): string {return x +' '+ y.join(' ')}
泛型
function identity<T>(arg:T):T{return arg
}const output = identity<string>("myString")
高级类型
// 交叉类型function extend<T,U>(first:T, second:U):T&U{let result =<T&U>{}for(let id in first){(<any>result)[id]=(<any>first)[id]}for(let id in second){if(!result.hasOwnProperty(id)){(<any>result)[id]=(<any>second)[id]}}return result
}classPerson{constructor(public name: string){}}interfaceLoggable{log():void}classConsoleLoggerimplementsLoggable{log(){
console.log(this)}}const jim =extend(newPerson("Jim"),newConsoleLogger())const n = jim.name
jim.log()const a =extend('1',false)// 联合类型functionpadLeft(value: string, padding: string | number): object {const result: object ={ value, padding }return result
}const indentedString =padLeft("Hello world",1)