简体   繁体   English

当我为一种类型分配具有默认值的多个泛型时,如何保持泛型类型推断?

[英]How can keep generic type inference when I assign one type with multiple generics with default value?

I define a function with multiple generics, and give them default types.我定义了一个具有多个泛型的函数,并为它们提供了默认类型。 For example:例如:

function fun<A = any, B = any>(a: A, b: B) {
  return [a, b] as const;
}

If I don't assign any types to them, the generics will be infered correctly.如果我不为它们分配任何类型,则将正确推断泛型。

let a: number;
let b: string;
const res = fun(a, b);  // [number, string]

But if I assign a certain type to part of them, the rest generics will be infered by their default types.但是如果我为其中的一部分分配了某种类型,其余的泛型将通过它们的默认类型来推断。

let a: number;
let b: string;
const res = fun<number>(a, b);  // [number, any]

How can I assign some generics as well as keeping the rest generics inferring themselves?我如何分配一些泛型并保持其余泛型自行推断?

Playground link 游乐场链接

I wouldn't think this would come up much, typically a will have the desired type so there's no reason for explicitly providing a type argument.我不认为这会出现很多,通常a将具有所需的类型,因此没有理由显式提供类型参数。 But in the cases where you want the result to be a different type from a (probably a supertype), the solution that comes to mind is to use as instead of a type argument.但是在您希望结果与a (可能是超类型)不同类型的情况下,想到的解决方案是使用as而不是类型参数。

Here's an example:下面是一个例子:

type NumList = 42 | 67;

declare let a: NumList;
declare let b: string;
const res1 = fun(a, b);  // [NumList, string]

const res2 = fun(a as number, b);  // [number, string]
//                ^^^^^^^^^^

Playground link 游乐场链接

In general I try to avoid type assertions, but that's effectively what providing the type argument would be anyway, and at least if the type assertion is wildly invalid it'll fail, for instance:一般来说,我尽量避免类型断言,但这实际上是提供类型参数的方式,至少如果类型断言非常无效,它将失败,例如:

declare let a2: string;
const res3 = fun(a2 as number, b);
//               ^^^^^^^^^^^^−−−−−−− error

Playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM