复制代码
抽象类和抽象方法
TS中的抽象类是提供其他类继承的基类,不能直接实例化。用abstract关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。
抽象类和抽象方法用来定义标准,来约束子类必须实现指定方法
abstract class Animal {
name:string
constructor(name:string){
this.name = name
abstract getVariety():any
run():void{}
class Dog extends Animal{
constructor(name:string){
super(name)
getVariety(){
return `${this.name}是只狗!`
const dog = new Dog('旺财')
console.log(dog.getVariety())
复制代码
TS中的接口
在OOP中,接口是一种规范的定义,它定义了行为和动作的规范,在程序设计里面,接口起到一种限制和规范的作用,接口定义了某一批类所需要遵守的规范,接口不关心这些类的内部装药数据,也不关系这些类里方法的实现细节,它只规定这批类里必须提供某些方法,提供这些方法就可以满足实际需要。
使用interface关键字来定义:
属性类型接口
interface AnimalInfo{
name:string
age:number
sex?:boolean
function Dog(info:AnimalInfo) {
console.log(`${info.name},${info.age}岁!`)
Dog({name:'mimi', age:2})
Dog({name:'mimi'})
复制代码
函数类型接口
interface encrypt {
(key:string,value:string):string
var md5:encrypt = function (key:string, value:string):string {
return key + value
md5('我是key', '我是value')
md5('我是key')
复制代码
可索引接口
interface userArry {
[index:number]:string
const arr:userArry = ['111122', '23333']
const arr:userArry = [123, '23333']
interface userObj {
[index:string]:string
const obj:userObj = ['22','333']
const obj:userObj = {a: '22', b: '333'}
复制代码
类类型接口
interface Animal {
name:string
getVariety():string
class Dog implements Animal{
name:string
constructor(name:string){
this.name = name
getVariety(): string {
return `${this.name}是只狗!`
const dog = new Dog('旺财')
复制代码
类类型接口和前面的抽象类相似,都是要求子类按照约定好的标准去具体实现。
接口的扩展
interface Dog extends Animal{
say():void
class NorthDog {
unClod():void{
console.log('北极狗不怕冷!')
class Husky extends NorthDog implements Dog{
name:string
constructor(name){
super()
this.name = name
getVariety(): string {
return `${this.name}是只狗!`
say(): void {
console.log('汪汪!!!')
const husky = new Husky('二哈')
husky.unClod()
复制代码
泛型
泛型是解决类、接口、方法的复用以及对不特定数据类型的支持。
泛型可以支持不特定数据类型,要求传入参数和返回的参数一致。
function getDate<T>(value:T):T {
return value
getDate<number>(123)
getDate<string>(123)
复制代码
泛型在class中的使用
class List<T>{
list:T[]
constructor(...list:T[]){
this.list = list
add(item:T):void{
this.list.push(item)
getList():T[]{
return this.list
const numList = new List<number>(1,2,3)
const stringList = new List<string>()
numList.add(8)
stringList.add('a')
console.log(numList.getList())
console.log(stringList.getList())
numList.add('a')
stringList.add(1)
复制代码
泛型接口
interface Config<T> {
name:T
getName():T
class Dog<T> implements Config<T>{
name:T
constructor(name:T){
this.name = name
getName(): T {
return this.name
const dog = new Dog<string>('旺财!')
console.log(dog.getName())
const dog = new Dog<string>(11)
复制代码