Typescript学习2

Typescript学习

抽象类

抽象类用abstract关键字定义,抽象类不能初始化实例。在抽象类中可以没有抽象方法,但有抽象方法的类必须声明为抽象类。子类必须实现抽象类中的抽象方法。

abstract class Animal {
  public speed: number
  constructor(speed: number) {
    this.speed = speed
  }
  abstract run(): any   // 抽象方法不需要实现,但是要指定一个类型
}

class Dog extends Animal {
  constructor(speed: number) {
    super(speed)
  }
  run() {   // 在继承抽象类必须要实现抽象类的抽象方法
    console.log(`${this.speed}`)
  }
}

接口

作用:在面向对象的变成中,接口时一种规范的定义,它定义行为和动作。在程序设计中,接口起到一种限制作用,接口定义某一批类所需要遵守的规范。接口不关心这些类中的数据状态,只规定这批类中必须提供某些方法,提供这些方法的类就可以满足实际需要。

  • ts中自定义方法传入参数对json进行约束
function printLabel(labelInfo: { label: string }): void {  // 规定传入参数必须要有label,是字符类型
  console.log(labelInfo)
}
let labelInfo = { label: "label" }
printLabel(labelInfo)
  • 对批量方法传入参数进行约束
interface FullName {   // 属性接口
  firstName: string
  secondName?: string  // 加上?为可选属性,可以传也可以不传
}

function printName(name: FullName) {
  console.log(`${name.firstName}+${name.secondName}`)
}
let Names = { firstName: "tom", secondName: "jack" }
printName(Names)
    
//  ajax 接口例子

interface Config {
  type: string
  url: string
  data?: string
  dataType: string
}

function ajax(config: Config) {
  let xhr = new XMLHttpRequest()
  xhr.open(config.type, config.url, true)
  xhr.send(config.data)
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("成功")
      if (config.dataType === "json") {
        console.log(JSON.parse(xhr.responseText))
      } else {
        console.log(xhr.responseText)
      }
    }
  }
}
ajax({
  type: "get",
  data: "name:zhangsan",
  url: "http://baidu.com",
  dataType: "json",
})
  • 类类型接口
// 类类型接口
interface Animal {
  name: string
  eat(str: string): void
}

class Dog implements Animal {
  name: string
  constructor(name: string) {
    this.name = name
  }
  eat(food: string) {
    console.log(str)
  }
}

// 拓展接口

interface Animal {
  eat(str: string): void
}
interface Person extends Animal {
  run(): void
}

class Programmer {
  public name: string
  constructor(name: string) {
    this.name = name
  }
  work() {
    console.log(`${this.name} is coding`)
  }
}

class undergraduate extends Programmer implements Person {
  constructor(name: string) {
    super(name)
  }
  eat(food: string) {
    console.log(`${this.name} is eating`)
  }
  run() {
    console.log(`${this.name} is running`)
  }
}

let person = new undergraduate("tom")
person.work()
person.eat("ice cream")
person.run()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值