Skip to content

Instantly share code, notes, and snippets.

@devmobasa
Created March 27, 2017 18:36
Show Gist options
  • Select an option

  • Save devmobasa/6bf89bad56e3cf0248077c32f7fe06cc to your computer and use it in GitHub Desktop.

Select an option

Save devmobasa/6bf89bad56e3cf0248077c32f7fe06cc to your computer and use it in GitHub Desktop.
Union Types in TypeScript
function print(text: string | string[]): string {
if (typeof text === 'string') {
return text;
}
// compiler now knows that you can use join
// and that variable type is definitely string[]
return text.join(' ');
}
let x = print('hello text');
let y = print(['hello', 'text', 'array']);
// let z = print(5); // Error: Argument of type '5' is not assignable to type 'string | string[]'
console.log(x);
console.log(y);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment