0
0
Typescriptprogramming~10 mins

Discriminated unions in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a discriminated union type for shapes.

Typescript
type Shape = Circle | Square;

interface Circle {
  kind: [1];
  radius: number;
}
Drag options to blanks, or click blank then click option'
A"circle"
B"radius"
C"square"
D"kind"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the property name instead of the string literal value.
Forgetting to use quotes around the string literal.
2fill in blank
medium

Complete the code to add a Square type to the discriminated union.

Typescript
interface Square {
  kind: [1];
  sideLength: number;
}
Drag options to blanks, or click blank then click option'
A"sideLength"
B"circle"
C"square"
D"kind"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong string literal for the kind property.
Confusing property names with discriminant values.
3fill in blank
hard

Fix the error in the function to correctly narrow the shape type using the discriminated union.

Typescript
function area(shape: Shape): number {
  if (shape.kind === [1]) {
    return Math.PI * shape.radius ** 2;
  } else {
    return shape.sideLength * shape.sideLength;
  }
}
Drag options to blanks, or click blank then click option'
A"radius"
B"circle"
C"square"
D"sideLength"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for the wrong discriminant value.
Using property names instead of discriminant string literals.
4fill in blank
hard

Fill both blanks to create a discriminated union and a function that returns the perimeter.

Typescript
type Shape = [1] | [2];

function perimeter(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return 2 * Math.PI * shape.radius;
    case "square":
      return 4 * shape.sideLength;
  }
}
Drag options to blanks, or click blank then click option'
ACircle
BSquare
CRectangle
DTriangle
Attempts:
3 left
💡 Hint
Common Mistakes
Using types not defined in the union.
Mixing unrelated shape types.
5fill in blank
hard

Fill all three blanks to define a discriminated union with a Triangle type and extend the area function.

Typescript
interface Triangle {
  kind: [1];
  base: number;
  height: number;
}

type Shape = Circle | Square | [2];

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.sideLength * shape.sideLength;
    case [3]:
      return 0.5 * shape.base * shape.height;
  }
}
Drag options to blanks, or click blank then click option'
A"triangle"
BTriangle
DSquare
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching discriminant strings and case labels.
Forgetting to add Triangle to the union type.