Typescript compiler wont make up it's mind on null vs undefined for method return

100 Views Asked by At

I am moving some code between existing projects and I am having an issue with typescript complaining about the return type of a method.

I don't know if it is a change in IDE or a compiler option so I can give you the config options if you need them. I'm a Java developer so JS and Typescript are new to me.

An example method is:

RoomPosition.prototype.findClosestByRangeThenPath = function <T extends _HasRoomPosition>(objects: T[]): T {
const distances = _.map(objects, obj => this.getRangeTo(obj));
const minDistance = _.min(distances);
if (minDistance > 4) {
    return this.findClosestByRange(objects);
 } else {
    const closestObjects = _.filter(objects, obj => this.getRangeTo(obj) == minDistance);
    return this.findClosestByPath(closestObjects);
 }
};

findClosestByRange and findClosestByPath both return T | null so I though I could make the method return the same but if I do the IDE is complaining "Type 'T | null' is not assignable to type 'T | undefined'."

My nieve solution is to assign findClosestByRange and findClosestByPath to a return value ret and do the following but it just smells bad.

if(ret){
      return ret;
  }else {
      return undefined;
  }

My questions are:

  1. Why is it saying that I need to return undefined when the return types of the methods in the function instead return null?

  2. Is there a better way to do it other than my fix above or putting @ts-ignore for each method with this problem?

Thanks for your help.

Edit: Adding the interface _HasRoomPosition

interface _HasRoomPosition {
    pos: RoomPosition;
}

For the full api it is here https://docs.screeps.com/api/

0

There are 0 best solutions below