Typescript中extends 和 implements

686 阅读1分钟

1.类继承的两种方式: extends和implements关键字

implements关键字 需要完全继承

interface Animal{
    age: number
    name: string
}
class Person implements Animal{
     age: number
     name: string
}
interface Animal{
    run(): void
}
class Person implements Animal{
    run(){ console.log"能跑")}
}

要继承的指定接口中的方法和属性都必须提供

extends 属性不需要每个提供

class Animal {
    constructor(kind){
        this.kind = kind;
    }
    run(){
        console.log("go")
    }
}
class Person extends Animal{
    constructor(kind){
        super(kind)
    }
    speak(){
        console.log("good")
    }
}
const xiao =  new Person("xiaoming")
xiao.kind
xiao.run()

Person继承了Animal的属性和方法 但是不必每个都提供

2.泛型约束

function getName<T extends {name: string}>(list: T[]):string[]{
    return list.map(item => item.name)
}

extends对入参限制,list每一项可以是一个对象, 但必须包含类型为string的name属性。 redux里面的dispatch一个action, 必须包含一个type

interface Dispatch <T extends {type: string}>{
    (action: T): T
}

3.条件类型与高阶类型 someType extends otherType ? TrueType: FalseType 判断是否能分配给另一个类型

type Person = {
    name: string
    age: number
}
type Student = {
    name: string
}
type Result = Student extends Person ? 'yes' : 'no' 
const test: Result = 'no'

链接: blog.csdn.net/qq_34998786…