首页 > 解决方案 > 打字稿:具有属性的函数

问题描述

我最近发现你可以在 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?

标签: typescript

解决方案


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

游乐场链接


推荐阅读