O'Reilly logo

Cross-platform Desktop Application Development: Electron, Node, NW.js, and React by Dmitry Sheiko

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Function type

We can set constraints on a function by using the function type literal:

const showModal: (toggle: boolean) => void =  
  function( toggle )  { 
    console.log( toggle ); 
  } 

I find it quite discouraging and prefer to use interface:

interface Switcher { 
  (toggle: boolean): void; 
} 
 
const showModal:Switcher = ( toggle ) => { 
  console.log( toggle ); 
} 
 
showModal( true ); 

You may now ask, what if the function has optional parameters? TypeScript makes it very simple to define an optional parameter. You just need to append the parameter with a question mark:

 function addOgTags(title: string, description?: string): string { return ` <meta property="og:title" content="${title}" /> <meta property="og:description" content="${description || ""}" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required