网站搜索

如何在 TypeScript 中“填充”泛型参数


假设我有一个像这样的通用 TypeScript 函数:

function doThing<T>(param: T): T {
    //...
}

而我有一个像这样的具体接口:

interface MyType {
    x: string;
    y: number;
}

我想重新导出 doThing 方法,使它假设泛型参数 T 总是 MyType。原因是这样我可以写成类似这样的类型:

doThing({

...编辑器会自动补全成员x和y,而我无需事先指定T。

我知道我可以做类似这样的事情:

import {doThing as _doThing} from 'some-module';
export const doThing = _doThing as (param: MyType) => MyType;

然而,这很笨重且容易出错。此外,doThing 实际上有比这个简化示例更多的成员和变体,因此需要大量的复制粘贴。

有没有办法简单地“填充”T,而不必复制粘贴整个原始定义?

答案#1

自 TypeScript 4.7 起,这段代码是允许的。

const foo: typeof doThing<MyType> = doThing

编辑:根据发行说明,行(1)也应该有效,但由于 TypeScript 4.8 中的一个错误,额外的括号(2)是必需的。

const foo = doThing<MyType>    // (1) error
const foo = (doThing)<MyType>  // (2) ok

答案#2

我想我们可以直接像这样使用这个函数:

let res = doThing<MyType>({x: "something", y: 0});