Generics 从TypeScript中函数的参数类型推断泛型类型参数

Generics 从TypeScript中函数的参数类型推断泛型类型参数,generics,typescript,type-inference,generic-programming,Generics,Typescript,Type Inference,Generic Programming,我想在TypeScript中创建一个toPlainObject()函数,并给出了一个工作示例: function toPlainObject<S extends D, D>(source: S) { return JSON.parse(JSON.stringify(source)) as D; } 签名函数toPlainObject(source:S extensed D){…}不起作用,并导致语法错误。也许我误解了你的意思,但我不明白你为什么不能这样做: interfac

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

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

签名
函数toPlainObject(source:S extensed 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());
接口是简单的{}
类示例实现ISample{}
函数toPlainObject(源:TInterface):TInterface{
将JSON.parse(JSON.stringify(source))作为TInterface返回;
}
让我们明白:ISample=toPlainObject(新样本());
您的示例也适用于我,没有问题(TypeScript 1.8.10)

接口是简单的{}
类示例实现ISample{}
函数toPlainObject(来源:S){
将JSON.parse(JSON.stringify(source))返回为D;
}
让我们明白:ISample=toPlainObject(新样本());

当然,我想的太复杂了:)你的解决方案可行,但是我仍然感兴趣的是如何通过从参数推断类型来实现这一点。@Dyna我已经更新了我的答案。你的样品适合我。所有泛型都是推断出来的,不需要提供它们。
let plain: ISample = toPlainObject<ISample>(new Sample());
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());
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());