0
0
Typescriptprogramming~10 mins

Never type and unreachable code 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 function that never returns.

Typescript
function fail(): [1] {
  throw new Error('This function never returns');
}
Drag options to blanks, or click blank then click option'
Anever
Bvoid
Cany
Dundefined
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'void' instead of 'never' for functions that throw errors.
Using 'any' which is too general.
2fill in blank
medium

Complete the code to make the switch statement exhaustive using the never type.

Typescript
type Color = 'red' | 'green' | 'blue';

function checkColor(c: Color) {
  switch(c) {
    case 'red':
      return 'Red';
    case 'green':
      return 'Green';
    case 'blue':
      return 'Blue';
    default:
      const _exhaustiveCheck: [1] = c;
      return _exhaustiveCheck;
  }
}
Drag options to blanks, or click blank then click option'
Anever
Bvoid
Cany
Dunknown
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'any' which disables type checking.
Not handling the default case at all.
3fill in blank
hard

Fix the error in the function that should never return but currently returns a value.

Typescript
function errorFunction(): never {
  [1] 'Error occurred';
}
Drag options to blanks, or click blank then click option'
Areturn
Bthrow
Cconsole.log
Dyield
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'return' with a string, which contradicts the 'never' return type.
Using 'console.log' which does not stop execution.
4fill in blank
hard

Fill both blanks to create an exhaustive check function using the never type.

Typescript
function assertNever(x: [1]): [2] {
  throw new Error('Unexpected value: ' + x);
}
Drag options to blanks, or click blank then click option'
Anever
Bstring
Dvoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' as parameter type which allows unexpected values.
Using 'void' as return type which implies function can return normally.
5fill in blank
hard

Fill all three blanks to handle all cases and use the never type for unreachable code.

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

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

function [3](x: never): never {
  throw new Error('Unexpected shape: ' + x);
}
Drag options to blanks, or click blank then click option'
AassertNever
Bs
Cnever
DhandleError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong function name in the default case.
Passing the wrong variable to the function.
Not using the never type in the function parameter.