使用prototype向Typescript类添加方法

使用prototype向Typescript类添加方法,typescript,prototype,Typescript,Prototype,我似乎无法使用prototype向我的Typescript类添加方法。Visual Studio警告我目标类型中不存在该函数 我读了一些关于为我的类型声明一个附加接口的内容,该接口将包括我要添加的方法的定义,但是我不太清楚在使用import导入我的类型之后应该如何做。事实上,我不能简单地做到: import { EcommerceCartItem } from "../classes/EcommerceCartItem"; interface EcommerceCartItem { m

我似乎无法使用prototype向我的Typescript类添加方法。Visual Studio警告我目标类型中不存在该函数

我读了一些关于为我的类型声明一个附加接口的内容,该接口将包括我要添加的方法的定义,但是我不太清楚在使用
import
导入我的类型之后应该如何做。事实上,我不能简单地做到:

import { EcommerceCartItem } from "../classes/EcommerceCartItem";

interface EcommerceCartItem {
    myMethod: any
}

EcommerceCartItem.prototype.myMethod = function () {
    return null;
};

…因为导入声明与电子商务项目的本地声明冲突。那么,我应该怎么做呢?

您必须在适当的模块中声明接口,以便将其作为扩展:

import { EcommerceCartItem } from "../classes/EcommerceCartItem";
declare module "../classes/EcommerceCartItem" {
    interface EcommerceCartItem {
        myMethod: any
    }
}

EcommerceCartItem.prototype.myMethod = function () {
    return null;
};

哦,太棒了,我不知道这个语法。非常感谢你。