自定义类型扩展方法打字稿

问题描述 投票:0回答:1

我已经为此苦苦了一段时间,我正在尝试将扩展方法添加到angular 8的自定义类型中,但是我无法让它们进行编译。有人可以告诉我我在做什么错。

export interface MyCustomType{
    name:string;
    id:number;
}

我尝试过的事情:1。

export {};
export interface MyCustomType{
   toString():string;
}

MyCustomType.prototype.toString() = funtion(){
  return 'this should work';
}

此未编译并显示错误:

找不到源文件中的错误:

  1.  declare module 'mytype'{
        export interface MyCustomType{
           toString():string;
        }
     }
    
     MyCustomType.prototype.toString() = funtion(){
       return 'this should work';
     }
    

未使用与上面相同的错误消息进行编译。

有人可以告诉我如何向我创建的接口添加扩展方法吗?不像Moment或Array

angular typescript extension-methods
1个回答
0
投票

一种替代方法是导出类而不是接口:

export class MyCustomType {
    name: string;
    id: number;

    toString(): string {
        return 'this should work';
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.