强类型与弱类型: 强类型限制实参和形参类型一致,不允许随意的隐式转换(编译层面就不允许),弱类型不限制,可以隐式转换。变量类型允许随时改变的特点,不是强弱类型的差异

  • 弱类型的问题
    1. 1. 类型异常只能等到运行时发现
  1. 类型不明确造成函数功能发生改变
  2. 类型不明确造成对象属性值的错误用法
  • 强类型的优势
    1. 1. 错误更早暴露
  1. 代码更只能,编码更准确
  2. 重构更牢靠
  3. 减少不必要的类型判断

    TypeScript

    TypeScript 是 JavaScript的超集,TypeScript包含了JavaScript的所有,并扩展类型系统、对es6的支持
    优点:ts的类型系统,更好的增强代码的可读性和可维护性,减少项目维护的成本
    缺点:增加了很多的概念,学习成本增加了也提高了项目开发的成本
    对象object类型可以接受函数,对象,数组。如果想只接受对象,需要用对象字面量形式{foo:number,bar:string}
    元祖类型:固定长度固定类型的数组
  • 示例
    const tuple: [number, string] = [18, ‘zec’]

    对象枚举

  • 示例
    enum status {
    draft = 0,
    published = 1
    }
    // ts中enum关键字表示枚举类型
    // 不指定值会默认从0开始累加
    // 可以是数字或者字符串类型
    // 枚举类型编译后会生成一个双向键值对对象
    const enum status {
    draft,
    published
    }
    // 常量枚举,编译后会移除

    隐式类型推断

  • 示例
    let age = 18 // 隐式推断为number,之后再赋值其他类型会报错
    let foo; // 声明变量没有赋值,则推断为any类型

    类型断言:明确告诉ts变量的类型

  • 示例
    const nums = [110, 120, 119, 112]
    const res = nums.find(i => i > 0) // ts推断res类型为number或者undefined
    const num1 = res as number // 明确res是一个number类型
    const num2 = res // 这种方式与JSX语法冲突

接口:用来约束对象的结构,对象实现一个接口,必须拥有这个接口定义的成员

  • 示例
    interface Post {
    title: string
    content: string
    subtitle?: string // 可选成员
    readonly summary: string // 只读成员
    }
    function printPost (post: Post) {
    console.log(post.title)
    console.log(post.content)
    post.summary = ‘123’ // 报错,不允许修改
    }
    // 显示要求传入的post参数必须要有title,content
    printPost({
    title: ‘’,
    content: ‘’
    })
    // 动态成员
    interface Cachee {
    [key: string]: string
    }
    const cache: Cachee = {}
    cache[‘name’] = ‘name’
    // 接口约束方法
    interface Eat {
    eat (food: string): void
    }
    interface Run {
    run (distance: number): void
    }
    // 实现接口的类必须有接口中定义的方法
    class Person implements Eat, Run {
    eat (food: string): void {
    }
    run (distance: number): void {
    }
    }

    泛型。

    定义函数,接口或者类的时候,没有指定具体的类型,使用时再指定具体类型

  • 示例
    // 将类型变成参数
    function createArray (length: number, value: T):T[] {
    const arr = Array(length).fill(value)
    return arr
    }
    const arr1 = createArray(3, 100)
    const arr2 = createArray(3, ‘foo’)