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

时间:2016-06-29 11:33:13

标签: generics typescript type-inference generic-programming

我想在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<D>(source: S extends D) { ... } 有效,导致语法错误。

1 个答案:

答案 0 :(得分:2)

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

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