typescript - 如何键入打字稿函数静态变量
问题描述
在 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”的对象的联合——但这不起作用。什么是正确的语法?
解决方案
您正在寻找呼叫签名:
type DescribableFunction = {
id: string;
(): void;
};
function dispatch(func: DescribableFunction) {
console.log('this should be strictly typed', func.id);
}
推荐阅读
- django - 如何更新 Django 中的数据库?
- python - 根据 pandas 中的行值创建新列
- ionic-framework - 如何在移动应用程序中使 Angular Material 的 mat-select 换行?
- javascript - 用于打开/关闭一排复选框的 Google 表格按钮
- javascript - 如何将此数据分组为可过滤
- javascript - 如何使布尔状态设置器可重用
- r - 一个因子内的ggplot构面网格
- python - 在新的 CSV 中合并 2 列,不想用新的空单元格复制占用的单元格
- firebase-cloud-messaging - Are FCM topics name globally unique?
- c# - 以字节形式获取图像并发送到 Facebook Api