typeScript 学习
1.基础类型
- 基础
let decLiteral: number = 6;
let decLiteral: string = '22';
let decLiteral: any = '22';
let decLiteral: number[] = [1, 2, 3]; / Array<number>
let decLiteral: [string, number] = ['xsa',2]; //元组
- 枚举
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];alert(colorName); // 显示'Green'因为上面代码里它的值是2 red如果=0 那就是blue
- 函数返回
声明一个void类型的变量没有什么大用,因为你只能为它赋予undefined和null
function warnUser(): void {alert("This is my warning message");
}
function warnUser(): boolean {return false
}function buildName(firstName: string = "Smith") {return firstName + " " + lastName;
}function buildName(firstName: string, ...restOfName: string[]) {return firstName + " " + restOfName.join(" ");
}
- Never
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {while (true) {}
}
- 类型断言as 我比TypeScript 更知道这个值的类型,听我的
let someValue: any = "this is a string";let strLength: number = (someValue as string).length;
2.变量声名
type C = { a: string, b?: number }
function f({ a, b }: C): void {// ...
}
3.接口 interface
interface LabelledValue {label: string;width?:number //可选readonly xxxx:number //只读 只有在创建的时候才可以修改[propName: string]: any; //key 为stringprivate state: any; //私有
}function printLabel(labelledObj: LabelledValue) {console.log(labelledObj.label);
}let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
- 继承接口
nterface Shape {color: string;
}interface Square extends Shape {sideLength: number;
}let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
4.泛型
<T> 有点像any 可以传入任意类型function loggingIdentity<T>(arg: T): T {console.log(arg.length); // Error: T doesn't have .lengthreturn arg;
}function loggingIdentity<T>(arg: T[]): T[] {console.log(arg.length); // Array has a .length, so no more errorreturn arg;
}