首页 > 解决方案 > 如何键入打字稿函数静态变量

问题描述

在 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);
}

在这个例子中,我已经完成了:函数 | { id:string } 说它是一个函数和一个带有“id”的对象的联合——但这不起作用。什么是正确的语法?

标签: typescriptfunctionstatictypescript-typings

解决方案


您正在寻找呼叫签名

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


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

推荐阅读