Can return types be conditionally null in TypeScript?

Viewed 36

I want this function to conditionally return a nullable type if it's given a nullable TGoalType or a non-nullable version of that type if it is supplied a non-nullable type.

function mapGoalType<TGoalType extends IParentGoal | undefined>(
  parentGoal: TGoalType
): null extends TGoalType ? MultiSelectOption | null : MultiSelectOption {
  if (!parentGoal) {
    return null; // Typescript complains here
  }
...
}

I tried code that is similar to Conditional types for nullable in Typescript but TypeScript isn't cooperating as it complains that I can't return null for a non-nullable return type. Is there a way to get TypeScript to understand what I want?

0 Answers
Related