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()