Multiple Types

Multiple Types
πŸ‘¨β€πŸ’Ό Sometimes a value can be one of several types. Union types let you express this.
🐨 Open
index.ts
and:
  1. Create a type ID that is string | number
  2. Implement formatId(id: ID): string β€” number IDs get a # prefix; string IDs are returned unchanged (including 0 and '')
  3. Create a type Result that is string | Error
  4. Implement processResult(result: Result): string β€” strings become Success: <value>; Errors become Error: <message>
  5. Export formatId and processResult by name

Completion criteria

  • Named exports: formatId, processResult
  • formatId(123) β†’ '#123'; formatId('abc') β†’ 'abc'; formatId(0) β†’ '#0'; formatId('') β†’ ''
  • processResult('Done!') β†’ 'Success: Done!'
  • processResult(new Error('Oops')) β†’ 'Error: Oops'
typeof checks if a value is a string, number, boolean, or symbol. For example, typeof value === 'string' returns true if value is a string.
instanceof checks if an object was created from a particular class. For example, value instanceof Error returns true if value is an Error object.

Please set the playground first

Loading "Multiple Types"
Loading "Multiple Types"