Introduction and use of interface in typescript

First of all, the interface is used to define a class structure, which is used to define which attributes and methods should be included in a class

for example:

Define our name and age through the interface, and then create an obj object to use

interface myInterface {
    
    
  name: string,
  age: number
}

const obj: myInterface = {
    
    
  name: 'sss',
  age: 11,
}

At the same time, the interface can also be used as a type declaration, and can be repeated declarations, and they can be merged by themselves

interface myInterface {
    
    
  name: string,
  age: number
}
interface myInterface {
    
    
  gender: string
}
const obj: myInterface = {
    
    
  name: 'sss',
  age: 11,
  gender: '22'
}

When we define a class, we can implement an interface. To implement an interface is to make the class meet the requirements of the interface.

interface myiNter {
    
    
  name: string;
  sayHello(): void;
}

class myClass implements myiNter {
    
    
  name: string;
  constructor(name:string){
    
    
    this.name = name;
  }
  sayHello(){
    
    
    console.log('哈哈')
  }
}

Guess you like

Origin blog.csdn.net/weixin_45389051/article/details/115285245