typescript是一门融合了部分后端 java思想的前端语言
可以不用,但是不可以不会
ts是强类型语言,打造强大的类型约束系统
TS就是写出约束力更强的系统,约束 JS的弱类型
image.png

Typescript是什么

  1. javascript that scales 可扩展的 js,ts是 js的超集
  2. 静态类型风格的类型系统
    1. 静态类型检查:为函数或变量添加约束
    2. 包括了es6 - es10的语法支持
  3. ts文档 https://www.typescriptlang.org/
  4. ts好的兼容性
    1. 完全兼容 es6+,ts的程序更容易理解
    2. 第三方库可以单独编写类型文件,declare
    3. 前端主流框架都用 ts重写
    4. 丰富的接口提示,代码自动补全,在不同的代码块和定义中进行跳

ts使用场景

ts内置类型

  1. document
  2. DOM
  3. BOM
  4. Date
  5. interface
  6. Utility Types
    1. https://www.typescriptlang.org/docs/handbook/utility-types.html
  1. interface Person {
  2. name: string,
  3. age: number
  4. }
  5. const user: Person = { name: 'lucy', age: 20 }
  6. type IPartial = Partial<IPerson>
  7. const user: IPartial = { name: 'lucy' } // Partial 可选的
  8. type IOmit = Omit<Person, 'name'> // 忽略的属性
  9. const user2: IOmit = { age: 20 }

类型推论

  1. Type Inference
  1. let str = 'lucy'
  2. str = 200 // 报错

联合类型

  1. Union Types
  2. |
  1. let str: string | number
  2. str = 'lucy'
  3. str = 200
  4. str.length // 报错
  5. str.toString() // 必须要访问共同的属性或方法
  6. const number: number | string = 25

类型断言

  1. Type Assertion
  2. as, value as number
  1. function getLength(value: string | number) {
  2. const str = value as string
  3. if (str.length) {
  4. return str.length
  5. }
  6. // 类型断言
  7. const number = value as number
  8. return number.toStirng().length
  9. }

类型保护

  1. Type Guard
  2. typeof
  3. instanceof
  1. function getLength(value: string | number): number {
  2. if (typeof value === 'string') {
  3. return value.length
  4. }
  5. // 类型保护,智能缩小范围
  6. return value.toStirng().length
  7. }

type类型别名

  1. type
  1. const sum: (x: number, y: number) => number
  2. const result = sum(10, 20)
  3. // type 类型别名
  4. type NumberType = (x: number, y: number, z?:number=20) => number
  5. const sum: NumberType
  6. const result = sum(100, 200)
  7. const add = function add(x: number, y: number, z:number=30): number {
  8. if (typeof z === 'number') return x + y + z
  9. return x + y
  10. }
  11. const add2: NumberType = add
  12. // 联合类型
  13. type StrOrNumber = string | number
  14. let result3: StrOrNumber = 123
  15. result3 = 'string'

字面量

  1. 特殊的类型
  1. const str: 'name' = 'name'
  2. const number: 1 = 1
  3. type Direction = 'Up' | 'Down' | 'Left' | 'Right'
  4. const goto: Direction = 'Left' // 只能是以上四选一

交叉类型

  1. &几种类型合并起来
  2. ‘&’和 interface的 extends类似
  1. interface Iname {
  2. name: string
  3. }
  4. type Person = Iname & {age: number}
  5. const person: Person = {name: 'lucy', age: 29}