Trying to set a generic class type from a method argument that will be called later presents a complex and challenging functionality. Unsure if TypeScript has the capability to handle this scenario...
The desired behavior is as follows:
class Class<T> {
foo = (bar: T[]) => {
/* ... */
return this;
};
baz = (cb: (qux: T) => void) => {
/* ... */
return this;
};
}
new Class() // Initial T is unknown
.foo([{ name: "John", id: "123" }]) // Inferred type of T is { name: string, id: string }
.baz((person) => null) // Type of person is { name: string, id: string }
Upon instantiation of the Class
, T
should remain unknown until an object array is passed to foo
, which then infers the type of T
. This inferred type is carried forward when passing a function to baz
where qux
is automatically typed accordingly.
No need to manually specify a generic to the Class
during instantiation as it should be inferred later on.
Thank you for your insights!