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?
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.type
could have other values than the two that you are checking.
This is why it thinks that there is unreachable code.