microsoft / microsoft/TypeScript
Generic interface callback return type validation issue
@weswigham is already working on this.
Since Jun 13, 2019.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: Version 3.5.0-dev.20190523
Search Terms:
union callback function flatMap overload
Code
interface I<A> {
foo<B>(f: (a: A) => B | I<B>): I<B>;
}
class C<A> implements I<A> {
constructor(readonly a: A) {}
public foo<B>(f: (a: A) => B | C<B>): C<B> {
const b: B | C<B> = f(this.a);
if (b instanceof C) {
return b;
}
return new C(b);
}
}
Expected behavior:
I expect that the example passes the type check without any errors based on the following assumptions: C<A> implements I<A> thus the return of C<A>.foo including f: (a: A) => B | C<B> matches the types declared in I<A>.foo.
Side Note: The interface of foo is similar to Array.flatMap.
Actual behavior:
I get the following type error for C<A>.foo:
Property 'foo' in type 'C<A>' is not assignable to the same property in base type 'I<A>'.
Type '<B>(f: (a: A) => B | C<B>) => C<B>' is not assignable to type '<B>(f: (a: A) => B | I<B>) => I<B>'.
Type 'C<B | I<B>>' is not assignable to type 'I<B>'.
Types of property 'foo' are incompatible.
Type '<B>(f: (a: B | I<B>) => B | C<B>) => C<B>' is not assignable to type '<B>(f: (a: B) => B | I<B>) => I<B>'.
Types of parameters 'f' and 'f' are incompatible.
Types of parameters 'a' and 'a' are incompatible.
Type 'B | I<B>' is not assignable to type 'B'.
Type 'I<B>' is not assignable to type 'B'.ts(2416)
I don
Playground Link:
https://codesandbox.io/s/hopeful-kirch-571v7?fontsize=14&module=%2Fsrc%2Findex.ts&view=editor
Related Issues:
Workaround:
One can workaround this issue using function overloading instead of a union return for the callback.
interface I<A> {
foo<B>(f: (a: A) => B): I<B>;
foo<B>(f: (a: A) => I<B>): I<B>;
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.