typescript - 实例化的多态函数作为 TypeScript 中的参数

标签 typescript

在下面的最后一行中,我想实例化一个多态函数并将其作为参数传递。

function id<T> (x:T) { return x; }
console.log ( id<number>(0) )
console.log ( id< (x:number)=>number > (id) (0) )
console.log ( id< (x:number)=>number > (id<number> ) (0) )

我得到 error TS1005: '(' expected.

所以看起来只有当我也调用函数时我才能实例化类型参数。真的吗?

省略实例化(倒数第二行)就可以了。

作为引用,这在 C# 中有效(注意:id<int>):

using System;
class P {
    static T id<T> (T x) { return x; }
    public static void Main (string [] argv) {
        Console.WriteLine (id<Func<int,int>> (id<int>) (0));
    }
}

嗯,我猜这在 TypeScript 中是不可能的。标准 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#4-expressions说“TypeScript 使用以下结构增强 JavaScript 表达式:......在函数调用中键入参数......”这显然意味着“仅在函数调用中键入参数”。

最佳答案

清理代码示例以明确目的。您需要以下内容:

function id<T>(x: T) { return x; }
(id<(x: number) => number>(id<number>))(0);

基本都想拥有id<number>作为一个变量。即:

function id<T>(x: T) { return x; }
let idNum = id<number>; // This is what you want

那是语法错误。您不能以这种方式创建具体类型。遗憾的是,您需要使用类型断言,将可靠性的重担放在肩上

let idNum = id as {(x:number):number};

关于typescript - 实例化的多态函数作为 TypeScript 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859911/

相关文章:

typescript - 类型 'string' 不可分配给类型 '{ value: string; }'

angular - 无法将 Angular5 HttpClient 响应映射到我的 typescript 类

javascript - 未处理的 promise 拒绝 [错误 : Got an invalid value for 'component' prop for the screen 'LocationType' . 它必须是有效的 React 组件。]

reactjs - 如何处理JSS中进度条值的颜色?

javascript - typescript : find date difference in dates/hours/minutes

reactjs - 错误: Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes<HTMLFormElement>'

javascript - 如何从 typescript 中的嵌套函数中调用函数?

javascript - Angular - 每 30 秒调用一次函数,但考虑运行该函数所需的时间

javascript - 使用 styled-components 的类型定义错误

node.js - Node 情况下的 Typescript IOC