Spooky
Spooky

Reputation: 39

Typescript: cannot run type alias example

I have been looking into Typescript documentation and I stumbled across type alias and this example here.

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}

Running this example as it is returns nothing as the doSomething function is not called anywhere. To actually describe what the function property does in the DescribableFunction type, I was thinking doing something like this but it won't work.

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}

const new_fn: DescribableFunction = {
  description: "test",
  () { // what do I put here?
    return true;
  },
};

doSomething(new_fn);

Upvotes: 0

Views: 54

Answers (1)

Tobias S.
Tobias S.

Reputation: 23925

You can use Object.assign() to instaniate an object assignable to this type.

const new_fn: DescribableFunction = Object.assign(
  (someArg: number) => { return true }, 
  { description: "test" }
)

Playground

Upvotes: 1

Related Questions