从 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)在不需要第一个泛型类型参数 S extends D 的情况下声明 toPlainObject这样我就可以通过执行以下操作来调用该函数:

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