Crhistian
Crhistian

Reputation: 1272

How to return the correct type from a chained method?

I have a service with two methods that I'd like to method chain and get typed information for.

const result = FirstMethod().SecondMethod();

Methods are defined like so:

FirstMethod(): any {
 // do some stuff
 return this;
} 

SecondMethod(): MyAwesomeType {
   return this.getMyAwesomeValue();
}

The problem is that result comes back as type any with no type information. I would expect that because my second method returns MyAwesomeType that i'd be able to get type information for that.

Obviously I can coerce the result to be the type that I might expect, but it doesn't provide much type safety if for example I were to put the wrong type there. What could I do?

Upvotes: 0

Views: 196

Answers (2)

jdavison
jdavison

Reputation: 322

I suppose this depends on your development environment, but in WebStorm it helped to define the return type of the first method.

enter image description here

@Rafael's answer says the same thing, but I it is think more explicit to label the return type as the class name rather than this.

Upvotes: 1

Rafael
Rafael

Reputation: 7746

Check out Advanced Types. Telling the compiler that you're returning any screws up type inference unless you encapsulate it in a class:

class Fooby {
    //instead of returning any here, consider returning `this`
    foo(): any /*returns Fooby instance*/ {
        return this;
    }

    betterFoo(): this /*returns Fooby instance, more explicit*/ {
        return this;
    }

    bar(): number {
        return 3;
    }
}

console.log(
    new Fooby().foo().bar()//3
);

Will not work as a function:

foo2(): any {
    return this;
}

bar2(): number {
    return 3;
}

console.log(
    foo2().bar2()
);

Upvotes: 1

Related Questions