【问题标题】:Infer generic type argument from parameter type of function in TypeScript从 TypeScript 中函数的参数类型推断泛型类型参数
【发布时间】:2016-11-01 02:06:18
【问题描述】:

我想在 TypeScript 中创建一个 toPlainObject() 函数并提出了这个工作示例:

function toPlainObject<S extends D, D>(source: S) {
    return JSON.parse(JSON.stringify(source)) as D;
}

现在我可以像这样调用函数了:

interface ISample {}
class Sample implements ISample {}

let plain: ISample = toPlainObject<Sample, ISample>(new Sample());

现在的问题是:有没有一种方法可以声明toPlainObject,而不需要第一个泛型类型参数S extends D,方法是使用第一个参数类型(即S),这样我就可以调用函数了只是在做:

let plain: ISample = toPlainObject<ISample>(new Sample());

签名function toPlainObject&lt;D&gt;(source: S extends D) { ... } 确实不起作用并导致语法错误。

【问题讨论】:

    标签: generics typescript type-inference generic-programming


    【解决方案1】:

    也许我误解了你的追求,但我不明白你为什么不能这样做:

    interface ISample {}
    class Sample implements ISample {}
    
    function toPlainObject<TInterface>(source: TInterface) : TInterface {
        return JSON.parse(JSON.stringify(source)) as TInterface;
    }
    
    let plain: ISample = toPlainObject(new Sample());
    

    您的示例也对我有用(TypeScript 1.8.10)

    interface ISample {}
    class Sample implements ISample {}
    
    function toPlainObject<S extends D, D>(source: S) {
        return JSON.parse(JSON.stringify(source)) as D;
    }
    
    let plain: ISample = toPlainObject(new Sample());
    

    【讨论】:

    • 当然,我想得太复杂了 :) 您的解决方案有效,但是我仍然对如何通过从参数推断类型来实现这一点感兴趣。
    • @Dyna 我已经更新了我的答案。你的样品对我有用。所有泛型都是推断出来的,不需要提供它们。
    猜你喜欢
    • 2016-12-05
    • 2020-03-11
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2020-07-10
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多