microsoft / microsoft/TypeScript
Generic interface callback return type validation issue
@weswigham ci sta già lavorando.
Dal 13/6/2019.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.4k
- Merge medio
- 1g 19h
- PR unite (30g)
- 117
Descrizione
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>;
}
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Valutazione
Questa issue non è ancora stata valutata.