TS(类)

1、interface接口可当tpe用;但是interface可以约束类的定义,按照特定的方式去创造类
interface classA{
name:string;
jump():void;
}
// 实现 implements
class A implements classA{
'name': string;
constructor(name : string){
this.name = name
}
jump(){
console.log(this.name, 'jump!')
}
}
console.log('xxxxx', (new A('an')).jump())

2、类的内部属性前缀
public 变量:内外部均可访问,子类可访问
private 变量:仅当前类可访问,子类不可访问,外部不可访问
protected 变量: 当前类和子类可访问,外部不可访问
简写:
Class Abc(){
constructor(public name, public age){
this.name = name;
this.age = age;
}
}

3、不确定的类型,使用泛型(不确定的类型)
function getYourself(a: T[]):T[]{
console.log({a})
return a
}
1) 声明泛型叫T
2) T[] 约定实参a 里面全是T类型的数组
3) T[] 约定返回值是: 全是T类型的数组
注意:T全程只有一个类型,不会变化

在调用时getYourself时,可以指定泛型类型;也可以不指定,不指定就ts自动推断
getYourself(['abc'])

4、类型断言
数据类型 unknown:未知的any类型

let unk : unknown
let str: string
错误写法:
str = unk
3种正确写法
1) str = unk as string
2) str = unk
3) if(typeof unk === 'string'){
str = unk
}

posted @ 2023-03-24 11:12  Math点PI  阅读(35)  评论(0)    收藏  举报