TypeScript 学习的随笔
TypeScript 是 JavaScript 的一个超集,支持 ECMAScript 6 标准
安装TypeScript
npm install -g typescript
编译
tsc app.ts
1 let message:string = 'holle world'; 2 console.log(message) 3 4 class Site{ 5 name():void{ 6 console.log(message) 7 } 8 } 9 let obj = new Site() 10 obj.name() 11 12 // let arr:number[] = [1,2,3] 13 let arr:Array<number> = [4,5,6] 14 console.log('数组:',arr) 15 16 let oarr:[number,string]; 17 oarr = [1,'a'] 18 console.log('元组:',oarr) 19 20 enum Color {Red,Green,Blue}; 21 let c:Color = Color.Blue 22 console.log('枚举:',c) 23 24 let str = '1' 25 let n:number = <number> <any>str;//断言 <Type>值 26 console.log(n) 27 28 // 接口 29 interface IPerson{ 30 name:string, 31 age:number, 32 sex:boolean, 33 action:(name:string)=>string 34 } 35 let xiaoming:IPerson = { 36 name:'小明', 37 age:18, 38 sex:true, 39 action:(name):string=>{ 40 return '我的名字叫'+name 41 } 42 } 43 let say:string = xiaoming.action(xiaoming.name) 44 console.log(say) 45 46 // 接口和数组 47 interface namelist{ 48 [index:number]:number 49 } 50 let iArr:namelist=[1,2,3]; 51 // iArr["a"] = 123 //可编译通过 运行报错 52 console.log(iArr) 53 54 // 接口继承 55 interface Musician extends IPerson{ 56 instrument:string 57 } 58 let xiaohong:Musician = { 59 name:'小红', 60 age:12, 61 sex:false, 62 instrument:'二胡', 63 action:(str):string=>{ 64 return str 65 } 66 }; 67 let say1:string = xiaohong.action('我会拉二胡'); 68 console.log(xiaohong.name,say1) 69 70 71 /* 72 interface type 73 相同点 74 interface 和 type 都可以描述一个对象或者函数 75 不同点 76 type 可以声明基本类型别名,联合类型,元组等类型 进行赋值 77 interface 能够声明合并 78 */ 79 type myType = { 80 name:string, 81 size:number 82 } 83 let isType:myType = { 84 name:'类型', 85 size:1 86 } 87 console.log(isType) 88 89 type alerType = 'success' | 'error' | 'info' 90 let alt:alerType; 91 // alt = 'abc' //报错 92 alt = 'success' 93 console.log('type',alt) 94 95 96 // 类 97 class Person{ 98 name:string; 99 constructor(name:string){ 100 this.name = name 101 } 102 sayHi():void{ 103 console.log('hi,我是'+this.name) 104 } 105 } 106 let xm = new Person('小明'); 107 xm.sayHi() 108 109 // 泛型 110 interface JJ{ 111 JJsize:number, 112 JJlength:number 113 } 114 interface Human{ 115 name:string, 116 age:number, 117 sex:string 118 } 119 function create<T extends JJ>(what:T):T{ 120 return what 121 } 122 123 let ren = create({ 124 name:'小明', 125 age:18, 126 sex:'男', 127 JJsize:12, 128 JJlength:18 129 }) 130 console.log(ren) 131 132 function create1<T>(c: { new ()}): T { 133 return new c() 134 } 135 let cArr = create1<Array<number>>(Array) 136 cArr[0] = 1 137 // cArr[1] = '2' //报错 138 console.log(cArr)
关于声明文件:https://www.runoob.com/typescript/ts-ambient.html