02.ts 1.1 KB

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