Home > Net >  Typescript: cannot run type alias example
Typescript: cannot run type alias example

Time:07-10

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

CodePudding user response:

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

  • Related