在指定其他类型时,如何让 TypeScript 推断受约束的泛型类型的值? [英] How can I have TypeScript infer the value for a constrained generic type when specifying additional types?

查看:21
本文介绍了在指定其他类型时,如何让 TypeScript 推断受约束的泛型类型的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In TypeScript, I have a function that accepts a generic parameter with constraints:

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

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

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

Now, I'm trying to make it so you can optionally add another type as part of the return type. However, when I do so, I must supply a default parameter for the U type. This makes it so TypeScript stops inferring the value of U and uses the default type that I supply:

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 的伪代码:

So my question is, is there a way I can have TypeScript keep inferring the type from the parameter? I don't want to supply a default type for U, I always want TypeScript to infer that value. Pseudo-code that shows full API how I'd like:

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!

推荐答案

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

Unfortunately this is not possible. There is a PR to add partial inference using the _ sigil, but it has been inactive for quite a while.

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

The only solution is to use function currying to get this behavior, although it is not ideal:

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' 

游乐场链接

这篇关于在指定其他类型时,如何让 TypeScript 推断受约束的泛型类型的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆