简体   繁体   中英

Why does method chaining in TypeScript cause generic type inference to fail?

I'm trying to build some sort of a "fluent API", and I also need to make use of generics, but TypeScript doesn't seem to like this combination!

Consider the following piece of code:

class Foo<T> {
    abc(arg: T) {
        return this;
    }
    xyz(arg: T) {
        return this;
    }
}

function getFoo<T>() {
    return new Foo<T>();
}

// 1. Without method chaining:
let v1: Foo<string> = getFoo();
v1.abc(/* The type of the "arg" parameter here is "string", which means that the type was inferred correctly. */);

// 2. With method chaining:
let v2: Foo<string> = getFoo().abc(/* The type of the "arg" parameter here is "unknown", which obviously means the type was NOT inferred correctly. */);

Am I doing something wrong or is this a limitation of TypeScript?

Are there any workarounds to get method chaining to work with generic inference?

The call on the right-hand side cannot use the type you declared in the left. It works if you instead pass the generic parameter in the call:

const foo = getFoo<string>().abc(...);

If you had to actually pass an an argument If the generic type, inference could also occur:

const foo = getFoo('foo').abc(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM