美文网首页我的学习之路
我的学习历程—— TypeScript(一)

我的学习历程—— TypeScript(一)

作者: Shiki_思清 | 来源:发表于2019-10-20 21:52 被阅读0次

简介

vue3.0采用TypeScript编写,可见其重要性。
TypeScript即超集于ES6, 核心为: 类型, 注解

准备工作

  1. 新建基于ts的项目 vue create tsdemo
    create.png

2.下载依赖 npm i

  1. 启动项目 npm run serve

组件创建方式

  1. 使用TS特性的模式(默认HelloWord中)
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'

@Component
export default class HelloWorld extends Vue {
  @Prop() private msg!: string
}
</script>
  1. 使用vue组件构造函数方式
<script >
import Vue from 'vue'
export default Vue.extend({
  data() {
    return { title: '组件构造函数方式' }
  }
})
</script>

3.使用.tsx后缀的文件创建组件

import { Component, Prop, Vue } from "vue-property-decorator";

@Component
export default class Comp1 extends Vue {
  foo = 'hello tsx'
  render() {
    return <div>{this.foo}</div>
  }
}

特殊文件说明

  1. shims-tsx.d.ts : 扩展后缀名为tsx文件
  2. shims-vue.d.ts : 扩展后缀名.vue 并且 所有vue文件必须是继承vue的一个子类

新特性

  1. 类型注解
let title1: string; //指定字符串类型
title1 = 'ABC'
// title1 = 123 // 报错
  1. 类型推论
let title2 = 'abc'
// title2 = 123 // wrong
  1. 数组类型
let names: string[];
// names = ['tom', 'jerry', 123] // 123wrong
  1. 任意类型 any 可用于数组
let foo: any;
foo = 'xx'
foo = 123
let list: any[]
list = [1, true, 'abc']
  1. 函数中的类型
function greeting(person:string): string{
  return 'hello' + person
}
greeting('qwe')
// greeting(123) // wrong
  1. 对象中的类型
let obj: {abc: string}
obj = {abc: 'abc'}
// obj = {abc: 123} // wrong
  1. 联合类型
let union: string | number
union = 'abc'
union = 123
  1. 函数
// function sayHello(name:string, age?:number): void{
function sayHello(name:string, age:number = 12): void{
  console.log(name + age);
}
sayHello('tom')
  1. 函数重载(参数数量或者类型,或者返回值类型区别多个同名函数,先声明,再实现)
function info(i: string): object
function info(i: object): string
function info(i: any): any {
  if (typeof i === 'object') {
    return i.name
  } else if (typeof i === 'string') {
    return { name: i }
  }
}
let myInfo = info({ name: '函数' })

未完

相关文章

网友评论

    本文标题:我的学习历程—— TypeScript(一)

    本文链接:https://www.haomeiwen.com/subject/elobpctx.html