代码之家  ›  专栏  ›  技术社区  ›  Greg Wozniak

在Typescript中使用外部抽象类而不扩展它

  •  1
  • Greg Wozniak  · 技术社区  · 7 年前

    我有一个模块叫做 utils.tsx 以便:

    interface IUtils {
        toUri: (route: string) => string
    }
    
    export default abstract class Utils implements IUtils {
        public toUri = (route: string) => {
            return route
        }
    }
    

    以及另一个我希望使用这个utils模块的文件:

     import Utils from '../helpers/utils'
    
     class Router  {
         private getBuilder = (search: string) => {
           const path = Utils.toUri(search)
         }
     }
    

    当我试图使用 Utils.toUri 我得到TS错误:

    [ts] Property 'toUri' does not exist on type 'typeof Utils'.

    我的意图是调用外部抽象类函数而不扩展 Router 类或从中继承(因为我在主文件中有多个外部模块)。

    public abstract toUri() 也也许我混淆了其他编程语言的例程,混淆了 静止的 具有 摘要 在这里

    1 回复  |  直到 7 年前
        1
  •  1
  •   jcalz    7 年前

    你不想 Utils IUtils 自从 公用事业 实例 类的类型。看起来你想要 公用事业 建造师 (其类型为 typeof Utils . 也就是说,你想要 toUri 成为一个 静止的 方法 公用事业 班级。这样地:

    abstract class Utils  {
      public static toUri = (route: string) => {
        return route
      }
    }
    

    没有办法注释 class Utils 声明声明类的静态端实现 IUtils公司 公用事业 IUtils公司 implements IUtils 在任何地方谢谢 structural typing :

    declare function takeIUtils(iUtils: IUtils): void;
    takeIUtils(Utils); // works anyway
    

    Router 使类按所需行为。


    公用事业 成为一个 公用事业 喜欢 class X extends Utils {...}; new X() 价值 :

    export const Utils : IUtils = {
      toUri(route: string) {
        return route
      }
    }
    

    namespace :

    export namespace Utils {
      export function toUri(route: string) {
        return route
      }
    }
    

    或者模块什么的。


    不管怎样,希望能有帮助。祝你好运