I found this issue in typescript. I have following example:
type AirplaneDTO = {
color?: string|null
owner?: string|null
}
type Airplane = {
color: string
owner: string
}
function isValidAirplane(airplane: AirplaneDTO): boolean {
return !!(airplane.color && airplane.owner);
}
function getValidAirplane(airplane: AirplaneDTO): Airplane|undefined {
if (!isValidAirplane(airplane)) {
return;
}
return {
color: airplane.color,
owner: airplane.owner,
}
}
As you can see, I am converting data from AirplaneDTO to Airplane. I don't want to set Airplane object if some of the fields in AirplaneDTO are null or undefined.
As I am doing this check if all the fields inside are set, TS does not recognize the "isValidAirplane" function-call and gives me following Error: Type 'string | null | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.(2322)
Is this an known Typescript issue or did I do something wrong here?
undefined?isValidAirplanea type predicate by changing the return type frombooleantoairplane is Airplane. More here.getValidAirplaneif you don't want to. You know the object that was passed in is a validAirplaneafter theisValidAirplanecall, so you could just return it.