繁体   English   中英

从TypeScript中的函数的参数类型推断通用类型参数

[英]Infer generic type argument from parameter type of function in TypeScript

我想在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());

现在的问题是:有没有一种方法可以通过使用第一个参数类型(即S )来声明toPlainObject而不需要第一个泛型类型参数S extends D ,以便我可以通过执行以下操作来调用函数:

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

签名function toPlainObject<D>(source: S extends D) { ... }不起作用并且在语法错误的结果。

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

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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM