我发现自己重复了很多代码,大致如下:
interface IMyInterface {
commonA: string;
commonB: string;
}
class Foo implements IMyInterface {
commonA: string = "hello";
commonB: string = "world";
foo: string = "Foo!";
}
class Bar implements IMyInterface {
commonA: string = "hello";
commonB: string = "world";
bar: string = "Bar!";
}
就我而言,我有许多类,它们都共享commonA
,commonB
但在其他方面有所不同。现在,我知道我无法在界面中设置默认值,但是是否有一些设计模式或 TS 构造允许我在一个地方定义默认值?
接口不应该有默认值或任何值,但您绝对可以使用抽象类来实现这一点。https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes
interface IMyInterface {
commonA: string;
commonB: string;
}
abstract class Base implements IMyInterface {
commonA: string = "hello";
commonB: string = "world";
}
class Foo extends Base {
foo: string = "Foo!";
}
class Bar extends Base {
bar: string = "Bar!";
}
更多关于抽象类和接口之间的区别:http : //dotnetpattern.com/typescript-abstract-class
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句