- interface只有成员的类型没有实现以及初始化
- class需要同时有成员的
类型和实现
interface PointInterface {
x: number
y: number
}
const p1:PointInterface = {
x: 1,
y: 2
}
// 要有默认值,不然严格模式下 ts 会报错
class PointClass {
// 这里的意思是初始化的时候 this.x = 0,和写在 constructor 的意思是一样的,都是进行初始化
x:number = 0
y:number = 0
}
// ---or---
class PointClass {
x: number
y: number
constructor(x = 0, y = 0){
this.x = x
this.y = y
}
}
const p2 = new PointClass(1,2)
console.log(p2)
- 上述声明简化:每个参数都要加
public
,并且public
只能用于typescript
class PointClass {
constructor(public x = 0,public y= 0){}
}
const p = new PointClass()
console.log(p)
-
constructor
也可以用重载
-
class
也可以使用索引签名
class Hash {
[s:string]: unknown
set(key:string,value:unknown){
this[key] = value
}
get(key:string){
return this[key]
}
}
-
class
实现接口
:implements
,实现
的意思就是你有的我都有
。但是interface里的可选属性
,在class
也依然要实现,不然使用时会报错
interface Person{
name: string
sayHi: (target: Person) => void
}
// User的类型只要是Person的子集就行,即被Person类型兼容就可以
class User implements Person{
constructor(public name:string){
}
sayHi(target:Person){
console.log(`Hi, ${target.name}`)
}
}
const user = new User('frank')
console.log(user.name)
-
class
还可以实现多个接口
,方法和一个接口类似,就是全部完善就行
-
class继承class
:
class Person {
constructor(public name:string){}
sayHi(){
console.log(`Hi, I am ${this.name}`)
}
}
class User extends Person {
id: number
constructor(name:string,id: number){
super(name) // 执行父类的构造函数
this.id = id
}
login(){}
sayHi(target?: User){
if(target === undefined){
super.sayHi()
}else{
console.log('我是 User 的 sayHi')
}
}
}
const user = new User('frank',1)
user.sayHi() // Hi, I am frank
user.sayHi(user) // 我是 User 的 sayHi
console.log(user)
class Person {
friend?: Person
constructor(public name:string,friend?:Person){
this.friend = friend
}
}
class User extends Person{
declare friend?: User
constructor(name:string,friend?:User){
super(name,friend)
}
}
const u1 = new User('frank')
const u2 = new User('ricky',u1)
console.log(u2.friend) // User 类型,不加declare的话,friend就是父类Person类型