12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- // 类型
- // number string boolean 字面量 any void
- // unknown never object array tuple enum
- // 隐式类型any
- let d;
- d = 10;
- d = "333";
- d = true;
- // 隐式any类型缺点,any值可以赋给其他不同类型
- let s: string;
- s = d;
- let e: unknown;
- // s = e; unknown不能赋值其他
- // unknown赋给其他值方法
- // 方法1.先判断
- if(typeof e === "string"){
- s = e;
- }
- // 方法2.类型断言
- s = e as string;
- // 另外写法
- s = <string>e;
- function fn(): void{}
- function fn1(): never{
- throw new Error('ddd');
- }
- // 指定属性,有问号的可以不对应
- let obj1: {name: string, age?: number};
- obj1 = {name: 'sss'}
- // 任意属性
- let obj2: {name: string, [propName: string]: any};
- obj2 = {name: 'sss', xxx:'sssss', xxxx: 23}
- let fff: (a: number, b: number)=> number;
- fff = function(n1: number ,n2: number):number{
- return n1 + n2
- }
- // 数组
- let arr: string[];
- let arr2: Array<number>
- // 元组,固定长度数组
- let h: [string, string];
- h = ['ss','ff']
- // 枚举
- enum Gender{Male,Female}
- let i: {name: string, gender: Gender};
- i = {name:'dd', gender: Gender.Female};
|