如何在TypeScript中将方法添加到泛型类的原型

时间:2018-09-26 09:10:07

标签: typescript

我正在尝试将方法添加到PromiseLike<T>的原型中 使用String没问题:

declare global {
    interface String {
        handle(): void;
    }
}

String.prototype.handle = function() {
}

编译正常

但是,如果我尝试对PromiseLike<T>执行相同操作,则会收到编译错误'PromiseLike' only refers to a type, but is being used as a value here.

declare global {
    interface PromiseLike<T> {
        handle(): PromiseLike<T>;
    }
}

PromiseLike.prototype.handle = function<T>(this: T):T {
    return this;
}

显然,这里的问题是PromiseLike是通用的。如何在打字稿中正确执行此操作?

2 个答案:

答案 0 :(得分:3)

接口在运行时不存在,在编译过程中会被擦除,因此无法在接口上设置函数的值。您可能正在寻找的是将该功能添加到Promise中。您可以类似地执行此操作:

declare global {
  interface Promise<T> {
      handle(): Promise<T>;
  }
}

Promise.prototype.handle = function<T>(this: Promise<T>): Promise<T> {
  return this;
}

答案 1 :(得分:0)

这不是答案,而是对“提香·切尔尼科娃·德拉戈米尔”的问题

这种方法怎么样,看起来可行。您看到这个有什么问题吗?

class ValueFlavours {
    initial?: number;
    changed?: number;
    audited?: number;
    calculated?:number
}

interface ValueFlavours {
    getValue: () => number | null ;
}

if (!ValueFlavours.prototype.getValue) {
    ValueFlavours.prototype.getValue = function () {
        // any shortcut to do this. I tried this.changed! But this does not handle zero;
        if (this.changed != undefined && this.changed != null) 
            return this.changed;
        if (this.calculated != undefined && this.calculated != null)
            return this.calculated;
        if (this.audited != undefined && this.audited != null)
            return this.audited;
        if (this.initial != undefined && this.initial != null)
            return this.initial;
        return null;
    };
}

const parseValueFlavour = function (s: any) {
    const v = new ValueFlavours();
    v.changed = s.changed
    v.initial = s.initial;
    v.calculated = s.calculated;
    v.audited = s.audited;
    return v;
};

// Parse all data coming from API, change at single place.
let data = parseValueFlavour({changed:null,  calculated: 10 });
// get value available to everywhere
console.log(data.getValue());