1

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/

Gathris
  • 105
  • 1
  • 1
  • 7
  • 1
    I don't know what `_HasRoomPosition` is, but the return type of `findClosestByRangeThenPath` is `T`, maybe you want it to return `T | null`? It's a guess though, there is not enough information. – Denis Frezzato Apr 14 '21 at 07:15
  • 2
    Can you create a minimal reproducible example in a [typescript playground](https://www.typescriptlang.org/)? It's hard to know how to help you here as is. – Alex Wayne Apr 14 '21 at 07:23
  • @DenisFrezzato returning T|null gives "Type 'T | null' is not assignable to type 'T | undefined'." – Gathris Apr 14 '21 at 07:50

0 Answers0