An Interface is something that describes an object or a function. You can think of it as shapes, what properties an object needs to have, what arguments a function needs to take or what values it returns, what arrays should look like, what descriptions a class and its descendants need to conform to, and so on. In the following seven parts, we’ll look at how object interfaces, function interfaces, indexable type interfaces, and class interfaces are defined, and how interfaces are used for interface inheritance, interfaces that define mixed types, and interfaces that inherit classes. πŸ“•

Object Interface

  1. Set the common properties that need to exist
  2. Set optional properties
  3. Setting read-only Properties
  4. Alternatively, you can use as or[propName: string]: anyTo specify other additional attributes that are acceptable
interface Person {
    name: stringbool? :boolean
    readonly timestamp: number
    readonly arr: ReadonlyArray<number> ReadonlyMap/ReadonlySet
}

let p1: Person = {
    name: 'oliver',
    bool: true.// βœ”οΈοΈ can set optional properties that are not necessary to write
    timestamp: + new Date(), // βœ”οΈ Set the read-only attribute
    arr: [1.2.3] // βœ”οΈ set the read-only array
}

let p: Person = {
    age: 'oliver'.// ❌ additional attributes
    name: 123 // ❌ type error
}

p1.timestamp = 123 // ❌ The read-only attribute cannot be modified
p1.arr.pop() // ❌ The read-only attribute cannot be modified
Copy the code

The function Interface

Interfaces can also be used to standardize the shape of functions. The function definition that needs to list the return value type of the parameter list in Interface. It is written as follows:

  1. Defines a function interface
  2. The interface accepts three parameters and does not return any values
  3. Use function expressions to define functions of this shape
Interface Func {// βœ”οΈ Specifies that this function takes two mandatory arguments of type number and an optional string argument desc. This function does not return any value (x: number, y: number, desc? : string): void } const sum: Func = function (x, y, desc = '') { // const sum: Func = function (x: number, y: Number, desc: string): void {console.log(desc, x + y)} sum(32, 22)Copy the code

Indexable type Interface

This Interface describes the shape of the index type and specifies the type of value returned by the index

interface StringSet {
    readonly [index: number]: string // ❗ Note that index can only be number or string
    length: number // βœ”οΈ can also specify attributes
}

let arr1: StringSet = ['hello'.'world']
arr1[1] = ' ' // βœ”οΈ can be set to read-only to prevent index assignments
let arr: StringSet = [23.12.3.21] // the ❌ array should be of type string
Copy the code

The class Interface

Interfaces can also be used to define the shape of a class. Note that the Interface class only checks instance properties. Static properties require an additional Interface; Such as:

// πŸ₯‡ PersonConstructor is used to check static parts
interface PersonConstructor {
    new (name: string, age: number) // βœ”οΈ this is used to check constructor
    typename: string // βœ”οΈ this is used to check the static property typename
    logname(): void // βœ”οΈ this is used to check static method logname
}
// πŸ₯ˆ PersonInterface is used to check the instance section
interface PersonInterface {
    // new (name: string, age: number) // ❌ static method checks cannot be written here
    log(): void // the instance method log is defined here
}

// class Person implements PersonInterface, PersonInterface {❌
const Person: PersonConstructor = class Person implements PersonInterface {
    name: string
    age: number
    static typename = 'Person type' // A static property named typename is defined
    static logname() { // A static method named logName is defined here
        console.log(this.typename)
    }
    constructor(name: string, age: number) { // Constructor is a static method
        this.name = name
        this.age = age
    }
    log() { Log is the instance method
        console.log(this.name, this.age)
    }
}
Copy the code

⚠️ Keep in mind that static properties and method checks are different interfaces than instance properties and methods

The Interface inheritance

As with class, use extens inheritance to update a new shape, for example inheriting the interface and generating a new interface that can be set to a new method check.

Take an example 🌰 :

interface PersonInfoInterface { // 1️ one here is the first interface
    name: string
    age: numberlog? () :void
}

interface Student extends PersonInfoInterface { // 2️ here inherits an interface
    doHomework(): boolean // βœ”οΈ adds a method check
}
interface Teacher extends PersonInfoInterface { // 3️ one interface is inherited here
    dispatchHomework(): void // βœ”οΈ added a method check
}

// Interface extends Student, Teacher // Also extends multiple interfaces

let Alice: Teacher = {
    name: 'Alice',
    age: 34,
    dispatchHomework() { // βœ”οΈ must satisfy the inherited interface specification
        console.log('dispatched')}}let oliver: Student = {
    name: 'oliver',
    age: 12,
    log() {
        console.log(this.name, this.age)
    },
    doHomework() { // βœ”οΈ must satisfy the inherited interface specification
        return true}}Copy the code

Interface of mixed type

Mixed-type interfaces use the same Interface to describe the properties or methods of a function or object, such as what parameters a function receives, what results it outputs, and what other methods or properties the function has. 🌰

interface Counter {
    (start: number) :void // 1️ one if only this one then this interface is a function interface
    add(): void // 2️ one more method here, then this interface is hybrid interface
    log(): number // 3️ here is another method
}

function getCounter() :Counter { // ⚠️ The function it returns must conform to three points of the interface
    let count = 0
    function counter (start: number) { count = start } // counter function
    counter.add = function() { count++ } // the add method increases count
    counter.log = function() { return count } // the log method prints count
    return counter
}

const c = getCounter()
c(10) // count defaults to 10
c.add()
console.log(c.log())
Copy the code

Interface inherits from the class

An Interface can inherit both an Interface and a class. In the process of creating subclasses, the description of the Interface must meet the description of the class that the Interface inherits

class Person {
    type: string // ❗️ here is a description of the class
}

interface Child extends Person { // the ❗️Child interface inherits from the Person class, so it specifies the Type attribute
    log(): void
    // There is a type: string
}

// The Child interface above ⚠️ inherits the description of type from Person and defines the log description of the Child interface itself

// πŸ₯‡
class Girl implements Child {
    type: 'child' // The interface inherits from Person
    log() {} // The interface itself is canonical
}

// πŸ₯ˆ the second way
class Boy extends Person implements Child { // First extends the Person class, then satisfies the description of the Child interface
    type: 'child'
    log() {}
}
Copy the code

The definition and use of this interface is shown below:

reference

  • Zhongsp. Gitbooks. IO/typescript -…
  • Ts.xcatliu.com/advanced/cl…
  • www.tslang.cn/docs/handbo…
  • www.typescriptlang.org/docs/handbo…