「写给自己看的」初识typescript

369 阅读1分钟

今天学了 typescript 的语法,typescript 的本质还是 javascript,它主要是为了让我们更早的检查错误,只需要比 js 多声明一个类型,就能在编译成 js 之前就能检查出错误。所以今天来讲讲编译、运行概念、typescript 本质和 typescript 语法。

一 、编译时与运行时的概念

2020-2-5-20-47-35.png
编译时:把一个语言编译成另一个语言
运行时:把一段可运行的代码放入一个可执行的环境里去运行
image.png

二、 typescript 的本质

2020-2-5-20-50-22.png

三、 Vue 单文件组件的 3 种写法


1.JS 对象

export default {data, props, methods, created...}

2.TS 类**<script lang='ts'>(推荐)**

@Component
export default calss XXX extends Vue{ 
xxx:string = 'hi';
@Porp(Nuber)yyy:number | undefined; }

 3.JS 类<script lang='js'>

@Component
export default class XXX extends Vue{ 
xxx = 'hi'; }

四、以一个 vue 转化为 typescript 语法的举例

<script lang="ts" >
import Vue from "vue";
import { Component,Prop } from "vue-property-decorator";
//从vue-property-decorator引入Component装饰器
@Component //使用装饰器,作用告诉TypeScript这个东西是vue组件
export default class Types extends Vue {
  //导出一个class,名字是组件名,继承 Vue
  type = "-";
@Prop(Number)xxx:number|undefined;
  selectType(type: string) {
    if (type !== "-" && type !== "+") {
      throw new Error("type is unknown");
    }
    //  点击时为"-"或者"+" , 动态绑定class:selected
    this.type = type; 
  }
}
</script>

这块的解释是

@Prop(Number)xxx:number|undefined;
  1. prop 告诉 Vue.xxx 不是 data 是 prop
  2. Number 告诉 Vue.xxx 运行时是个 Number
  3. xxx 是属性名
  4. number | undefined 告诉 TS xxx 的编译时类型

五、总结

所以 typescript 的好处有

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