Currently, I am working on creating a filter function that takes a generic parameter and ensures that the return type of the given function is either the input if it matches the generic or null
if it does not.
type A = { type: 'A' };
type B = { type: 'B' };
type Union = A | B;
const filter = <T extends Union>(filter: <E extends Union>(item: E) => E extends T ? E : null) => {
// something
};
filter<A>((item) => {
// Argument of type '<E extends Union>(item: E) => E | null' is not assignable to parameter of type '<E extends Union>(item: E) => E extends A ? E : null'.
// Type 'E | null' is not assignable to type 'E extends A ? E : null'.
// Type 'null' is not assignable to type 'E extends A ? E : null'.(2345)
if (item.type === 'A') return item;
return null;
});
I am perplexed as to why this code snippet is not functioning as intended. The error message seems misleading, as I believe TypeScript fails to recognize that
if (item.type === 'A') return item;
actually satisfies the E extends A ? E
condition?
One possible alternative could be using a type guard, although this approach would not guarantee that all types of T
will be returned.