【问题标题】:How to write a class which can implement an interface in TypeScript如何编写一个可以在 TypeScript 中实现接口的类
【发布时间】:2019-12-07 02:12:06
【问题描述】:

我是 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 中做到这一点?

【问题讨论】:

标签: javascript typescript interface


【解决方案1】:

使用 implements 关键字让你的类实现接口:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-07-20
  • 2019-03-04
  • 2016-10-27
  • 2021-07-31
  • 2015-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多