今天学了 typescript 的语法,typescript 的本质还是 javascript,它主要是为了让我们更早的检查错误,只需要比 js 多声明一个类型,就能在编译成 js 之前就能检查出错误。所以今天来讲讲编译、运行概念、typescript 本质和 typescript 语法。
一 、编译时与运行时的概念
编译时:把一个语言编译成另一个语言
运行时:把一段可运行的代码放入一个可执行的环境里去运行
二、 typescript 的本质
三、 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;
- prop 告诉 Vue.xxx 不是 data 是 prop
- Number 告诉 Vue.xxx 运行时是个 Number
- xxx 是属性名
- number | undefined 告诉 TS xxx 的编译时类型
五、总结
所以 typescript 的好处有
- 类型提示:更智能的提示
- 编译时报错:还没有运行代码的时候就知道自己写错了
- 类型检查:无法点出错误的属性