簡體   English   中英

如何鍵入打字稿函數靜態變量

[英]How to type typescript function static variable

在 Javascript(和 Typescript)中,您可以靜態地向函數添加變量,因為它是第一類對象。 我想這樣做是為了向函數添加元數據。 我怎樣才能輸入這個來強制函數有一個特定的靜態變量?

function doThing() {
   console.log('thing done!')
}
doThing.id = 'myThingId';

function dispatch(func: Function | { id:string }) { // <-- what is this type, 
  console.log('this should be strictly typed', func.id);
}

在我完成的示例中:Function | { id:string } 說它是一個函數和一個帶有“id”的對象的聯合——但這不起作用。 什么是正確的語法?

您正在尋找呼叫簽名

type DescribableFunction = {
  id: string;
  (): void;
};


function dispatch(func: DescribableFunction) {
  console.log('this should be strictly typed', func.id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM