繁体   English   中英

来自默认值的 Typescript 泛型类型推断

[英]Typescript generic type inference from default value

考虑以下函数。

public static convert<T, U>(t: T, conversion: ((toutput: T) => U) = ((t) => toutput)) { 
    return conversion(t);
}

Typescript 当前抱​​怨从转换函数返回的 toutput 参数,这是默认参数。

我试图让 IDE 认识到,给定默认参数,T 与 U 相同。

我的用例如下:

convert(1) // returns 1
convert(1, x => ({x})) // returns an object with { x : 1 }

有没有人知道让编译器静音并能够在上面正确创建此函数的方法?

我认为你可以通过重载来实现这一点:

public static function convert<T>(t: T): T;
public static function convert<T, U>(t: T, conversion: (t: T) => U): U;
public static function convert<T, U>(t: T, conversion?: (t: T) => U) {
    return conversion ? conversion(t) : t;
}

..

const foo = convert(1)             // inferred type 1
const bar = convert(1, x => ({x})) // inferred type { x : number }

1被加宽为number因为隐式文字类型在返回值的上下文中被加宽(例如x => ({x}) ),这反过来导致T推断为number 您可以通过显式键入第一个参数来避免这种情况:

const bar = convert(1 as 1, x => ({x})) // inferred type { x: 1 }

像这样尝试:

static convert<T, U = T>(t: T, conversion: ((toutput: T) => U) = t => t as T & U) {
  return conversion(t);
}

const x = convert(1);
const y = convert(1, x => ({x}));

使用T作为U默认值,并将conversion函数的默认值的返回类型conversionT & U

暂无
暂无

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

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