02.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // 类型
  2. // number string boolean 字面量 any void
  3. // unknown never object array tuple enum
  4. // 隐式类型any
  5. let d;
  6. d = 10;
  7. d = "333";
  8. d = true;
  9. // 隐式any类型缺点,any值可以赋给其他不同类型
  10. let s: string;
  11. s = d;
  12. let e: unknown;
  13. // s = e; unknown不能赋值其他
  14. // unknown赋给其他值方法
  15. // 方法1.先判断
  16. if(typeof e === "string"){
  17. s = e;
  18. }
  19. // 方法2.类型断言
  20. s = e as string;
  21. // 另外写法
  22. s = <string>e;
  23. function fn(): void{}
  24. function fn1(): never{
  25. throw new Error('ddd');
  26. }
  27. // 指定属性,有问号的可以不对应
  28. let obj1: {name: string, age?: number};
  29. obj1 = {name: 'sss'}
  30. // 任意属性
  31. let obj2: {name: string, [propName: string]: any};
  32. obj2 = {name: 'sss', xxx:'sssss', xxxx: 23}
  33. let fff: (a: number, b: number)=> number;
  34. fff = function(n1: number ,n2: number):number{
  35. return n1 + n2
  36. }
  37. // 数组
  38. let arr: string[];
  39. let arr2: Array<number>
  40. // 元组,固定长度数组
  41. let h: [string, string];
  42. h = ['ss','ff']
  43. // 枚举
  44. enum Gender{Male,Female}
  45. let i: {name: string, gender: Gender};
  46. i = {name:'dd', gender: Gender.Female};