浅析 TypeScript

99 阅读1分钟

查看最新版 TypeScript

    npm info typescript version

用法

<script lang="ts">
  import Vue from 'vue'
  import {Component} from 'vue-property-decorator';

  @Component
  export default class Types extends Vue{
  
    // @Prop(Number)  xxx: number | undefined;
    // Prop 告诉 Vue, xxx 不是 data 是 prop
    // Number 告诉 Vue xxx 运行时是个 Number
    // xxx 属性名
    // number | undefined 告诉 TS xxx 的编译时类型
    
    type = '-'    // 数据
    selectType(type: string){   // 方法, 用到的TS语法: type: string 给type添加类型
      if (type !== '-' && type !== '+'){
        throw new Error('type is unknown')
      }
      this.type = type
    }
    created(){}
    mounted(){}
  }
</script>

使用方式

  • 必须要用 class, 用装饰器
  • 可以直接写 data, methods, props, 生命周期

TypeScript 自动加分号

  • Settings --> Editor --> Code Style --> TypeScript --> Punctuation

image.png

优势

  • 类型提示: 更智能的提示
  • 类型检查: 无法点出错误的属性
  • 编译时报错: 还没运行代码就知道自己写错了

TS 的本质

  • JS: 类型
  • 类型用来检查 JS 语法是否正确(编译报错)
  • 删掉类型编译为可运行JS