【发布时间】:2021-12-09 00:02:45
【问题描述】:
我正在尝试输入一个过滤器函数,该函数接受一个泛型参数并强制给定函数的返回类型是输入(如果它与泛型匹配)或null(如果不是)。
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;
});
我不太明白为什么这不起作用。我想错误信息有点误导,我怀疑 TS 不理解 if (item.type === 'A') return item; 实际上满足 E extends A ? E 部分?
我想我也可以使用类型保护,但这不会强制返回所有类型的 T。
【问题讨论】:
标签: typescript