数据类型

TS - 图1

  1. number
  2. string
  3. boolean
  4. array ```javascript // 声明数组方式1 let arr: (number | string | boolean)[] = [1, 2, 3, ‘4’, true] console.log(arr);

// 声明数组方式2 - 范型 type objInfo = {name: string, age: number} let arr2: Array = [1,2,3,’4’, true, {name: ‘wuyanbin’, age: 12}] console.log(arr2);

  1. 5. tuple
  2. 6. 联合类型: union
  3. 7. 字面量类型:literal
  4. 8. 枚举类型:enum
  5. ```javascript
  6. enum Role {
  7. Reporter = 1,
  8. Developer = 3,
  9. Maintainer = 10,
  10. Owner = 12,
  11. Guest = 110
  12. }
  13. console.log(Role.Developer) // 3
  14. console.log(Role[110]) // "Guest"
  1. any

TS + any = JS

  1. unknow

保证类型的安全,相对比any好些

  1. void

函数永远没有返回值

  1. function say(){
  2. console.log('lala');
  3. }
  1. undefined
  2. never

一个函数永远无法执行完成

  1. function throwError(msg, code){
  2. throw{
  3. msg,
  4. code
  5. }
  6. }
  7. throwError('找不到了', 404)
  1. 类型适配(类型断言) Type Assertions

人为告诉计算机类型

  1. let message: any;
  2. message = '123'
  3. message.endWith('c')
  4. // 声明方式1
  5. let ddd = (<string>message).endWith('c')
  6. // 声明方式2
  7. let ddd = (message as string).endsWith('3')