使用 webext-bridge 我可以定義我的聽眾
// 墊片.d.ts
declare module 'webext-bridge' {
export interface ProtocolMap {
// define message protocol types
// see https://github.com/antfu/webext-bridge#type-safe-protocols
'event-name': { helloMessage: string };
}
}
// 代碼
onMessage('event-name', (message) => {
// do something strict way
console.log(message.data.helloMessage); // no ts error
});
我如何定義第二個引數的方法,例如
function onEventName(message: /* How to get message type dynamically here? */) {
console.log(message.data.helloMessage); // ts not able to get type here
}
onMessage('event-name', onEventName);
uj5u.com熱心網友回復:
它可以定義為:
import { onMessage, ProtocolMap, IBridgeMessage } from 'webext-bridge'
function onEventName(message: IBridgeMessage<ProtocolMap['event-name']>) {
console.log(message.data.helloMessage);
}
onMessage('event-name', onEventName);
TS玩
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524775.html
標籤:打字稿