Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading