【问题标题】:How to type typescript function static variable如何键入打字稿函数静态变量
【发布时间】:2021-11-09 03:44:11
【问题描述】:

在 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”的对象的联合——但这不起作用。正确的语法是什么?

【问题讨论】:

    标签: typescript function static typescript-typings


    【解决方案1】:

    您正在寻找Call Signature:

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

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 2020-05-21
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      相关资源
      最近更新 更多