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

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

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

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


新特性

10.class 类

class MyComp {
  private _foo: string // 私有属性,不能再累的外部访问
  protected bar: string // 保护属性,可以在派生类中访问
  readonly biu = 'biu' // 只读属性必须在声明时或构造函数里初始化
  static: nova = 'nova' // 通过类名访问

  // 参数加上修饰符,并直接赋值形参
  constructor(private boom = 'boom') {
    this._foo = 'foo'
    this.bar = 'bar'
  }

  // 存取器:存储数据的时候课添加额外逻辑,在vue里面可以用作计算属性
  get foo() {
    return this._foo
  }
  set foo(val) {
    this._foo = val
  }
}
  • class内部可以声明private, protected, public, readonly, static
  • 声明过的属性必须直接赋值或在构造函数中进行赋值,否则会报错
  • private属性如果想暴露给外部,则需要进一步声明get set函数

11.interface 接口

interface Person {
  firstName: string
  lastName: string
}
function fullName(person: Person) {
  return 'Hello, ' + person.firstName + ' ' + person.lastName
}
const user = { firstName: 'Jane', lastName: 'Bob' }
console.log(fullName(user))

通过interface对对象结构进行约束
如果传参不是约定的对象类型,则不会通过编译

  1. implements 实现
class Greeter implements Person {
  constructor(public firstName: string, public lastName: string) {}
}

想要实现一个类,继承Person,那么必须在构造函数里把Person中的参数重新声明

  1. <T> 泛型
// 定义基础对象格式,即为下面的data
interface Feature {
  id: number
  name: string
}
// 定义一个返回值类型, 此处可传递泛型T,且返回值data类型为T
interface Result<T> {
  ok: 0 | 1
  data: T
}
// 定义一个方法,确定返回值为上面定义的Result格式,且定义data为T类型
function getData<T>(): Result<T> {
  const data: any = [{ id: 1, name: '类型注解' }, { id: 2, name: '编译型语言' }]
  return { ok: 1, data }
}
// 调用
@Component
export default class HelloWorld extends Vue {
  features: Feature[] = [] // 初始化数组,并确定类型
  private created() {
    const { ok, data } = getData<Feature[]>() // 可以直接结构处返回值result
    if (ok) {
      this.features = data // 此时data即为Feature[]
    }
  }
}
  1. 装饰器

装饰器就是一个工厂函数,经过处理,返回一个函数

  • Prop
import { Component, Vue, Prop } from 'vue-property-decorator' // 将Prop引入进来
// @Component({
  // props: {
  //   msg: {type: String, default: ''} // 此时String是给vue用的
  // }
// })
@Component
export default class HelloWorld extends Vue {
  @Prop({ type: String, required: true }) // 此处是对vue来说的
  private msg!: string // 此处是对TS来说的

此时在调用HelloWorld组件的时候,msg属性变成了必传项

  • Emit
  • Watch
  title = 'ts特性'
  @Watch('title')
  onChangeTile(val: string, oldVal: string) {
    // dosomething
  }

相关文章

网友评论

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

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