【问题标题】:Return the function input if it extends the generic type, otherwise null如果它扩展了泛型类型,则返回函数输入,否则返回 null
【发布时间】: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 playground

【问题讨论】:

    标签: typescript


    【解决方案1】:

    我不确定为什么filter 函数的返回类型必须是E extends T ? E : null。里面有条件,不确定是否允许。

    这个简化版可以编译:

    type A = { type: 'A' };
    type B = { type: 'B' };
    
    type Union = A | B;
    const filter = (filter: <E extends Union>(item: E) => E | null) => {
      // something
    };
    
    
    
    filter((item) => {
      if (item.type === 'A') return item;
    
      return null;
    });
    
    

    【讨论】:

    • 对,它不需要是E extends T ...,但我想确保它返回item,只有当它适合作为Tnull或其他我传入的类型时否则可以辨别。
    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多