interface

The keyword of the interface is interface

interface IStudent {
    name: string
    no: number
}

function say(stu: IStudent) {
    console.log(stu)
}
say({ name: 'hhh'.no: 1 })

Copy the code

Optional attribute

interface IStudent {
    name: string
    no: numbertag? :string // Optional attribute
}

function say(stu: IStudent) {
    console.log(stu)
}
say({ name: 'hhh'.no: 1 })
say({ name: 'haha'.no: 2.tag: 'Merit Student' })

Copy the code

Read-only property, keyword readonly

interface IStudent {
    readonly firtName: string
    name: string
    no: numbertag? :string
}

function say(stu: IStudent) {
    console.log(stu)
}
let stu1: IStudent = { name: 'Joe'.no: 1.firtName: '张' }
let stu2: IStudent = { name: 'bill'.no: 2.tag: 'Merit Student'.firtName: 'li' }
// stu1.firtName = 'king'
console.log(stu1.firtName)
say(stu1)
say(stu2)

Copy the code

Declare functions with interfaces

interface ISay1 {
    (name: string) :string
}
let say1: ISay1 = (str1: string) = > { return str1 }
let say2: ISay1 = (str1: string) = > { return str1 }
// function say1(st1: string): string {
// return st1
// }
console.log(say1('say1'), say2('say2'))
Copy the code

Indexable type of interface

Declared array

interface StringArray {
    [index: number] :string;
}
let myArray: StringArray;
myArray = ["Bob"."Fred"];

Copy the code

Statement of the map

interface IMap {
    [key: string] :string;
}
let m: IMap = { "a": "a" }
console.log(m)
Copy the code

Class type, interface constraints on class

// Interfaces focus on constraints
interface ILee {
    firstname: string
}

class Lee implements ILee {
    firstname: string
}
let lee = new Lee()
lee.firstname = 'Lee'

console.log(lee)
Copy the code

Inheritance of interfaces

interface IAnimal {
    name: string
}
interface ICat extends IAnimal {
    say(str: string) :string
}
interface IDog extends IAnimal {
    say(str: string.s2: string) :string
}
class Cat implements ICat {
    name: string
    say(s1: string) :string {
        return s1
    }
}
// Interfaces focus on signatures, i.e. constraints
class Dog implements IDog {
    name: string
    say(s1: string.st2: string) :string {
        return s1 + st2
    }
}
let cat: ICat = new Cat()
console.log(cat.say('cat'))
let dog: IDog = new Dog()
console.log(dog.say('dog1'.'dog2'))
Copy the code