typescript - 打字稿:具有属性的函数
问题描述
我最近发现你可以在 JS 中做到这一点:
function foo() {
console.log("FOO");
}
foo.bar = "FOOBAR";
foo(); // logs "FOO"
console.log(foo.bar); // "FOOBAR"
现在我的问题是:如何在打字稿中表达这种对象/函数,例如将它作为参数传递给另一个函数时?
这显然会引发错误......
type Foo = () => void;
function test(foo: Foo) {
console.log(foo.bar); // Property 'bar' does not exist on type '() => void'.ts(2339)
}
除了将其声明为any
?
解决方案
interface
您可以使用带有调用签名的 an 来表达:
interface FunctionWithBar {
(): void; // <=== Makes this callable, in this case accepting no params
// and returning nothing
bar: string; // Also has a `bar` proprerty of type string
}
function example(f: FunctionWithBar) {
f();
console.log(f.bar);
}
function foo() {
console.log("FOO");
}
foo.bar = "FOOBAR";
example(foo);
推荐阅读
- php - 搜索过滤器 laravel 问题,从获取值
- mysql - 从在线服务器恢复截断的表
- vue.js - 验证为真后如何在vue js中隐藏错误消息?
- ruby-on-rails - rails-ujs 永久禁用链接
- ios - siri 快捷按钮 (INUIAddVoiceShortcutButton) 在有多个快捷方式 (NSUserActivity) 时显示错误的标题
- oracle - 在oracle中将两个不同表中的记录插入到单个表中
- android - 如何使用媒体扫描仪减少媒体的扫描时间?
- scala - Spark Structured Streaming Kafka 集成 偏移管理
- c++ - 使用 Libssh 将文件从服务器复制到客户端:分配文件复制目标路径的问题
- java - 用于实例化泛型类中使用的对象实例的工厂方法