【问题标题】:How can I have TypeScript infer the value for a constrained generic type when specifying additional types?在指定其他类型时,如何让 TypeScript 推断受约束的泛型类型的值?
【发布时间】:2020-10-10 21:19:55
【问题描述】:

在 TypeScript 中,我有一个接受带有约束的泛型参数的函数:

function f1<U extends string>(param: U): U {
  return param;
}

const a1 = f1('hello');
// a1's type is 'hello' -- Great!

现在,我正在尝试制作它,以便您可以选择添加另一种类型作为返回类型的一部分。但是,当我这样做时,我必须为 U 类型提供一个默认参数。这使得 TypeScript 停止推断 U 的值并使用我提供的默认类型:

function f2<T = never, U extends string = string>(param: U): U | T {
  return param;
}

const b1 = f2('hello');
// b1's type is 'hello' -- Great!

const b2 = f2<boolean>('hello');
// b2's type is string | boolean -- Terrible: I want the type to be 'hello' | boolean.

const b3 = f2<boolean, 'hello'>('hello');
// b3's type is 'hello' | boolean -- Poor: The type is correct but API is redundant.

所以我的问题是,有没有办法让 TypeScript 继续从参数推断类型?我不想为 U 提供默认类型,我总是希望 TypeScript 推断出该值。显示我想要的完整 API 的伪代码:

function f3<T = never, U extends string = infer>(param: U): U | T {
  return param;
}

const c1 = f3('hello');
// c1's type is 'hello' -- Great!

const c2 = f3<boolean>('hello');
// c2's type is 'hello' | boolean -- Great!

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    很遗憾,这是不可能的。有一个PR 可以使用_ sigil 添加部分推理,但它已经有一段时间不活动了。

    唯一的解决方案是使用函数柯里化来获得这种行为,尽管它并不理想:

    function f2<T = never>() {
      return function <U extends string = string>(param: U): U | T {
        return param;
      }
    }
    const b2 = f2<boolean>()('hello');
    // b2's type is string | 'hello' 
    
    

    Playground Link

    【讨论】:

    • 公关停滞了太可惜了,这肯定是一个不错的功能!
    猜你喜欢
    • 2019-10-13
    • 1970-01-01
    • 2021-06-23
    • 2022-11-23
    • 1970-01-01
    • 2019-09-17
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多