【问题标题】:Is it possible to specify that a class implements an abstract class after declaration?是否可以指定一个类在声明后实现一个抽象类?
【发布时间】:2019-10-29 16:58:05
【问题描述】:

我想声明一个抽象类和一个类而不声明该类在同一个文件中实现了抽象类。

abstract class ExampleAbstractClass {
    abstract exampleMethod(): string;
}

class ExampleClass {
    exampleMethod(): string { return 'test'; }
}


// I would like to specify that the class does implement the abstract class in another file
ExampleClass implements ExampleAbstractClass

Playground

这种用例可以在其他语言中使用,例如带有协议的 Swift。

【问题讨论】:

    标签: typescript typescript-class


    【解决方案1】:

    是的,有可能:

    example-class.ts

    export abstract class ExampleAbstractClass {
        abstract exampleMethod(): string;
    }
    
    export class ExampleClass {
        exampleMethod(): string { return 'test'; }
    }
    
    export interface ExampleClass extends ExampleAbstractClass {} // NOTICE: usage of interface!
    

    example-class.test.ts

    import { ExampleClass, ExampleAbstractClass } from "./example-class";
    
    const a: ExampleAbstractClass = new ExampleClass(); // works!
    console.log(a.exampleMethod());
    

    你必须使用interfaceclass,因为class declaration merging is currently disallowed in TypeScript。您还可以使用augment the module 在单独的文件中使用declare module "<path to implementation source file>" {} 定义和实现ExampleClass

    【讨论】:

    • 谢谢,这很有趣。我看到这并没有强制执行 abstract 类定义中的任何内容。你会看到如果你在ExampleClass中去掉exampleMethod()的实现就没有编译错误。
    • @ebuat3989 我在发布之前检查过,当我将exampleMethod() 定义为返回number 而不是string 的函数时,它确实出错了。无论如何,这不是我会使用的设计,因为它看起来很容易损坏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2013-06-19
    • 2011-01-10
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多