Multiple Types
Multiple Types
π¨βπΌ Sometimes a value can be one of several types. Union types let you express
this.
π¨ Open
and:
- Create a type
IDthat isstring | number - Implement
formatId(id: ID): stringβ number IDs get a#prefix; string IDs are returned unchanged (including0and'') - Create a type
Resultthat isstring | Error - Implement
processResult(result: Result): stringβ strings becomeSuccess: <value>; Errors becomeError: <message> - Export
formatIdandprocessResultby 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.