Skip to content

TS: Narrowing - Discriminated unions #15

@mkermani144

Description

@mkermani144

Description

Complete the following code using discriminated unions, so that TS gives no errors:

interface Base {
  foo: string;
  bar: string;
}

interface A extends Base {
  bazA: string;
}

interface B extends Base {
  bazB: string;
}

type AOrB = A | B;

const aOrB: AOrB = {
  foo: 'foo',
  bar: 'bar',
  ...(Math.random() > 0.5 ? { bazA: 'bazA' } : { bazB: 'bazB' }),
}

if (/* condition for a */) {
  console.log('aOrB is an A', aOrB.bazA);
} else {
  console.log('aOrB is a B', aOrB.bazB);
}

process.exit(0);

You need to add a mechanism to implement coditions.

What to google

  • discriminated unions (also called discriminated types or tagged types)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Status

✅ Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions