1

I recently discovered that you can do this in JS:

function foo() {
  console.log("FOO");
}

foo.bar = "FOOBAR";

foo(); // logs "FOO"
console.log(foo.bar); // "FOOBAR"

Now my question is: How can I express this kind of object/function in typescript, e.g. when passing it to another function as a parameter?

This obviously throws an error...

type Foo = () => void;

function test(foo: Foo) {
  console.log(foo.bar); // Property 'bar' does not exist on type '() => void'.ts(2339)
}

Any ideas other than declaring it as an any?

3 Answers 3

1

You can add a call signature and bar property to Foo type:

type Foo = {
    () : void;
    bar: string
}

function test(foo: Foo) {
  console.log(foo.bar); 
}

Alternatively write it as intersection:

type FooFn = () => void;
type Foo2 = FooFn & {bar: string}

function test2(foo: Foo2) {
  console.log(foo.bar); 
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

1

You can express that with an interface with a call signature:

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

Playground link

Comments

0

You can also try to merge function with namespace, a more typescript approach as shown below,

function foo() {
  console.log("FOO");
}
namespace  foo {
  export const bar = "FOOBAR";
}

foo(); // logs "FOO"
console.log(foo.bar); // "FOOBAR"

function test(f: typeof foo) {
  console.log(f.bar); // Property 'bar' now exists
}

2 Comments

Why is this a „more typescript“ approach? Never really used namespaces before...
by that, I mean TS can merge function with namespace, a feature more "unique" to TS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.