如何编写可以在TypeScript中实现接口的类

时间:2019-07-29 17:39:25

标签: javascript typescript interface

我是TypeScript的初学者。我下面有一段代码

async function sleep(ms: number) {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(), ms)
    })
}

async function randomDelay() {
    const randomTime = Math.round(Math.random() * 1000)
    return sleep(randomTime)
}

class ShipmentSearchIndex {
    async updateShipment(id: string, shipmentData: any) {
        const startTime = new Date()
        await randomDelay()
        const endTime = new Date()
        console.log(`update ${id}@${
            startTime.toISOString()
            } finished@${
            endTime.toISOString()
            }`
        )

        return { startTime, endTime }
    }
}

// Implementation needed
interface ShipmentUpdateListenerInterface {
    receiveUpdate(id: string, shipmentData: any)
}

我必须编写一个实现ShipmentUpdateListenerInterface的类。如何在TypeScript中做到这一点?

1 个答案:

答案 0 :(得分:2)

让您的类使用Implements关键字实现接口:

class  ShipmentUpdate implements ShipmentUpdateListenerInterface {
    receiveUpdate(id: string, shipmentData: any){
    }
}