Optional parameters

When a function's parameter is strictly typed, it feels rigid when the function needs to be flexible. Why should we pass in index to our previous example in a situation where we intend to return the whole string if the index is missing? 

When the index parameter is omitted while calling the function, TypeScript will throw an error. To overcome this issue, we can declare the index parameter as optional:

function stringIndex(char: string, index?: number): string {  // Just return string as is  // if index is not passed in  if(!index) return char;  // else, return the index   // that was passed in  const arr = char.split(' ')  return arr[number];}

The question mark succeeding the parameter name tells TypeScript that it's okay if ...

Get TypeScript 2.x for Angular Developers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.