Home > Enterprise >  Why TypeScript forces me to return in unreachable code?
Why TypeScript forces me to return in unreachable code?

Time:03-03

I have this code:

import { Point, LineString } from 'geojson';

export function getIconPoint(geometrie: Point | LineString): Point {
  if (geometrie.type === 'Point') {
    return geometrie;
  }

  if (geometrie.type === 'LineString') {
    return {
      type: 'Point',
      coordinates: geometrie.coordinates[0],
    }
  }

  // unreachable
}

After the two if statements the code is supposed unreachable because Point and LineString are discriminated interfaces based on their type field. Still TypeScript is not happy and asks me to return something, but I don't want to add anything else than Point as the return value type:

Function lacks ending return statement and return type does not include 'undefined'

How do I fix this in a clean way?

TypeScript playground

CodePudding user response:

In that case why not just omit the else?
If you have only two options that is..

import { Point, LineString } from 'geojson';

export function getIconPoint(geometrie: Point | LineString): Point {
  if (geometrie.type === 'Point') {
    return geometrie;
  }

  return {
    type: 'Point',
    coordinates: geometrie.coordinates[0],
  }
}

Ditto if you had more options btw, simply omit the last condition.
Typescript shouldn't complain when it's written like this.

Obviosuly to make it even better we would probably prefer to employ an exhaustive type-checking function of sorts.

CodePudding user response:

geometrie.typecould have other values than the two that you are checking.

This is why it thinks that there is unreachable code.

  • Related