前言
简单记录一下TypeScript常用的几个类型,做模板用 >.>
模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| let x:any = 1;
let str: string = "Hello World";
let num: number = 5;
let flag: boolean = true;
let arr: number[] = [1, 2]; let arr2: Array<number> = [1, 2];
let list: [string, number]; list = ['hello', 666];
enum Color {Red, Green, Blue} let c: Color = Color.Blue; console.log(Color); console.log(c);
let num = 2; let num2;
|
// 函数
1 2 3
| function prt(str: string): void { console.log(str) }
|
// 传参是参数可以缺少但不能多
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
| class Shape { Area:number
constructor(a:number) { this.Area = a } }
class Circle extends Shape { disp():void { console.log("圆的面积: "+this.Area) } }
interface A { num:number prt(str: string): number }
class B implements A { num:number; num2:number;
constructor(a:number,b:number) { this.num = a; this.num2 = b; }
prt(str: string) { console.log(str); return 123; } }
|
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
| interface A{ firstName:string, lastName:string, say: ()=>string }
const xxx1: A = { firstName: "Tom", lastName: "jack", say: (): string => { return "Hello" } };
interface A{ age:number }
interface B extends A{ name:string }
const xxx2 = <B>{}; xxx2.age = 27; xxx2.name = "xpengp";
interface A{ v1:number }
interface B{ v2:number }
interface C extends A, B{ }
const xxx3: C = {v1: 12, v2: 23};
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export interface Options { name: string, age: number, address: string }
const DefaultOptions: Options = { name: 'xxx', age: 18, address: 'China' };
export function person(options: Options): object { return Object.assign(DefaultOptions, options); }
|
导入模板
1 2 3 4
| const {person} = require('./models/module'); console.log(person({ age: 12 }));
|
- 上例实现了默认参数的实现,可见极大地方便了代码的重构
- 同时方便了IDE的使用
总结
- 项目中TS文件需要先编译为js再执行
- 未完待续。。。