打字稿:通用类型设置后调用函数/方法

Tho*_*ont 1 typescript

对于一个项目,我会把一个函数的实现和这个函数的调用分开。

它是这样的:

function identity<T, R>(arg: T): R {
    return { result: arg };
}

const test = identity<string, { result: string }>;

console.log(test('test'))

Run Code Online (Sandbox Code Playgroud)

我收到此错误:“测试不是函数”

有没有办法像这样执行类型提示?

谢谢

Mal*_*lio 5

在这里,这就是我认为您正在尝试做的事情:

type R<U> = {
    result: U
};

function identity<T>(arg: T): R<T> {
    return { result: arg };
}

const test : (a: string) => R<string> = identity;
Run Code Online (Sandbox Code Playgroud)

这是思考同一件事的另一种方式:

type R<U> = {
    result: U
};

type RFunc<T> = (a: T) => R<T>;

const identity = function<T>(arg: T): R<T> {
    return { result: arg };
}

const test : RFunc<string> = identity;
Run Code Online (Sandbox Code Playgroud)