0
0
Typescriptprogramming~10 mins

Exhaustive checking with never 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 declare a variable with type never.

Typescript
let errorValue: [1];
Drag options to blanks, or click blank then click option'
Aunknown
Bany
Cvoid
Dnever
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'any' instead of 'never' because 'any' allows any value.
Confusing 'void' with 'never'.
2fill in blank
medium

Complete the function signature to indicate it never returns.

Typescript
function fail(message: string): [1] {
  throw new Error(message);
}
Drag options to blanks, or click blank then click option'
Avoid
Bstring
Cnever
Dundefined
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'void' which means returns nothing but does return.
Using 'string' or 'undefined' which are incorrect here.
3fill in blank
hard

Fix the error in the exhaustive check function by completing the switch default case.

Typescript
function assertNever(x: never): never {
  throw new Error("Unexpected value: " + [1]);
}
Drag options to blanks, or click blank then click option'
AJSON.stringify(x)
Bx
Ctypeof x
DString(x)
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof x which returns a string describing the type, not the value.
Using JSON.stringify(x) which may cause runtime errors if x is never.
4fill in blank
hard

Fill both blanks to complete the exhaustive check in the switch statement.

Typescript
type Shape = { kind: 'circle', radius: number } | { kind: 'square', size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius * shape.radius;
    case 'square':
      return shape.size * shape.size;
    default:
      return [1](shape); // call assertNever
  }
}

function [2](x: never): never {
  throw new Error('Unexpected shape: ' + x);
}
Drag options to blanks, or click blank then click option'
AassertNever
BcheckNever
DfailNever
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the function call and declaration.
Not calling the function in the default case.
5fill in blank
hard

Fill all three blanks to complete the exhaustive check with a switch and assertNever function.

Typescript
type Result = { type: 'success', value: number } | { type: 'error', message: string };

function handleResult(result: Result): string {
  switch (result.type) {
    case 'success':
      return `Value is ${result.value}`;
    case 'error':
      return `Error: ${result.message}`;
    default:
      return [1]([2]); // call assertNever with result
  }
}

function [3](x: never): never {
  throw new Error('Unexpected result: ' + x);
}
Drag options to blanks, or click blank then click option'
AassertNever
Bresult
Dfail
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the wrong variable to the function.
Using a different function name in call and declaration.