【问题标题】:Functions with generics used as parameters in other functions具有泛型的函数在其他函数中用作参数
【发布时间】:2020-06-12 21:03:47
【问题描述】:

假设我这样定义一个类型CoolType

type CoolType<T> = {message: string, result: T} 

然后我定义一个CoolFunction类型来描述一个返回CoolType的函数:

type CoolFunction = <T>() => CoolType<T>

CoolFunction 是第二个函数期望的参数类型:

function superCoolFunction(coolFunction: CoolFunction) {
    return coolFunction()
}

最终,在所有这些定义之后,我尝试运行一些这样的代码:

const res = superCoolFunction(<string>() => {
    return {message: 'I am the message', result: 'I am the result'}
})

但是,在上述代码的&lt;string&gt;() =&gt; { 上,我从编译器那里得到一个错误,告诉我

'string' 已声明,但它的值永远不会被读取。ts(6133) 的参数 类型 '() => { 消息:字符串;结果:字符串; }' 不是 可分配给“CoolFunction”类型的参数。来电签名 返回类型'{消息:字符串;结果:字符串; }' 和 'CoolType' 不兼容。 这些类型之间的“结果”类型不兼容。 类型“字符串”不可分配给类型“T”。 “字符串”可分配给“T”类型的约束,但“T”可以用不同的约束子类型实例化 '{}'.ts(2345)

知道我做错了什么吗?这是重现错误的stackblitz

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    您似乎在错误的地方使用了泛型。我想你想要的是:

    type CoolFunction<T> = () => CoolType<T>;
    

    CoolFunctions 也采用泛型类型。然后你的高阶函数可以传播泛型:

    function superCoolFunction<T>(coolFunction: CoolFunction<T>): CoolType<T> {
        return coolFunction();
    }
    

    现在编译器可以推断出具体的类型了:

    superCoolFunction(() => ({ message: 'foo', result: 123 }));
    // function superCoolFunction<number>(coolFunction: CoolFunction<number>): CoolType<number>
    

    或明确提供:

    superCoolFunction<string>(() => ({ message: 'foo', result: 'bar' }));
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2010-10-04
      • 2016-07-02
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 2018-11-16
      相关资源
      最近更新 更多