ts学习笔记(二)----高级类型

上一节拉下的typeof

// typeof可以在类型上下文中引用变量或类型
let p = { x: 1, y: 2}

function formatPoint(point: typeof p){}

1.class

(1)

 (2)class的构造函数没有返回值,不能为其指定返回值

class person {
    name:string
    age:number
    constructor(name: string, age: number){
        this.name = name
        this.age = age
    }
}
//构造函数里的this指向实例对象

let p1 = new person('zs', 18)

(3)class的实例方法

class point {
    x=10
    y=10

    scalc(n: number) {
        this.x *= n
        this.y *= n
    }
}

let p1 = new point()  //因为没有写构造函数,所以参数不写
p1.scalc(10)
console.log(p1)

(4)类继承extends(类与类)

// 类继承extends
class animal{
    move(){
        console.log('走两步')
    }
}

class dog extends animal {
    name="二哈"
    say(){
        console.log('汪汪')
    }
}

const dog1 = new dog()

dog1.move()
dog1.say()

(5)实现接口(类与接口之间)

// 实现接口(类与接口)
// 类必须要实现接口里所有的属性和方法
interface sing {
    say(): void
}

class singer implements sing {
    say(): void {
        console.log('小苹果')
    }
}

const singer1 = new singer()
singer1.say()

(6)class可见修饰符

protected只在类中或子类中可用,在实例化对象中不可用

private只在当前类中可用,在子类和实例化对象中都不可用

扫描二维码关注公众号,回复: 17027938 查看本文章

(7)只读修饰符readonly

只能修饰属性,不能修饰方法,readonly修饰的属性只能在构造函数中修改,其他地方都不能修改

 2.类型兼容性

 

 (2)接口之间兼容性(多的赋值给少的)

(3)函数兼容性

①参数个数

 

 ②参数类型

统一位置的参数类型要相同,(少的可以赋值给多的)

③返回值类型

 3交叉类型&

interface person {
    name: string
}

interface contant {
    phone: string
}

type personDetail = person & contant

let person1: personDetail = {
    name: 'zs',
    phone: '11111'
}

 4泛型

 简化是手动传入的类型可以省略不写

 泛型约束

 传的参数只要有length属性就行

 

猜你喜欢

转载自blog.csdn.net/m0_63237100/article/details/130082826