Defining Union Types

TopicSource
๐Ÿฆ’ TypeScriptTypeScript course by the native web

Union types give you a way to limit the possible values for a property.

Imagine a shop with different brand names:

type Brand =

'your-shop.de' |

'your-shop.com' |

'your-shop France';

  

const getTitle = function (brand: Brand): string {

return `${brand} shop`;

};

  

console.log(getTitle('your-shop.com'));

Or some platform configurations:

type OperatingSystem = 'macOS' | 'Linux' | 'Windows';

type Browser = 'Chrome' | 'Firefox' | 'Safari';

interface Platform {

operatingSystem: OperatingSystem;

browser: Browser;

}

  

const chromeOnWindows: Platform = {

browser: 'Chrome',

operatingSystem: 'Windows'

}
export {};

You can also use unions with interfaces:

interface UnversionedPlatform {
  operatingSystem: string;
  browser: string;
}

interface VersionedPlatform {
  operatingSystem: string;
  operatingSystemVersion: string;
  browser: string;
  browserVersion: string;
}

// we either want versions for both, or not at all
type Platform = UnversionedPlatform | VersionedPlatform;

// this doesn't work, because we are missing browserVersion
const platform: Platform = {
  operatingSystem: 'macOS',
  operatingSystemVersion: 'Catalina',
  browser: 'Chrome'
};

export {};

  1. Interfaces in TypeScript
  2. Common types in TypeScript