1. 程式人生 > 其它 >【TypeScript】介面

【TypeScript】介面

技術標籤:前端typescript

介面

介面是物件的狀態(屬性)和行為(方法)的抽象(描述)
介面: 是一種型別,一種規範,一種規則,一種約束

    // id是number型別, 必須有, 只讀的
    // name是string型別, 必須有
    // age是number型別, 必須有
    // sex是string型別, 可以沒有

    interface IPerson {
        // readonly: 只讀
        readonly id: number
        name: string
        age: number
        // ?: 可有可無
sex?: string } let person: IPerson = { id: 1, name: 'kudo', age: 18, sex: '男' } console.log(person) person.name = '張三' console.log(person)

在這裡插入圖片描述

函式型別

    // 函式型別: 通過介面的方式作為函式的型別來使用

    // 定義一個介面,用來作為某個函式的型別使用
    interface ISearchFunc {
        // 定義一個呼叫簽名
(source: string, subString: string): boolean } // 定義一個函式,該型別就是上面定義的介面 const searchString: ISearchFunc = function(source: string, subString: string): boolean { // 在source中查詢subString, 返回true或false return source.search(subString) > -1 } //呼叫函式 console
.log(searchString('哈哈哈,我好帥', '帥'))

在這裡插入圖片描述

類型別

    // 定義一個介面
    interface IFly {
        // 該方法沒有任何的實現
        fly()
    }

    // 定義一個類,這個類的型別就是上面定義的介面
    class Bird implements IFly {
        fly() {
            console.log('我會飛')
        }
    }

    // 例項化物件
    const bird = new Bird()
    bird.fly()


    // 定義一個介面
    interface ISwim {
        swim()
    }

    // 定義一個類,這個類的型別是IFly和ISwim
    class Person implements IFly, ISwim {
        fly() {
            console.log('我會飛')
        }
        swim() {
            console.log('我會游泳')
        }
    }
    const person = new Person()
    person.fly()
    person.swim()

    // 介面可以繼承多個介面
    interface IMyFlyAndSwim extends IFly, ISwim {}

在這裡插入圖片描述