Skip to content

Instantly share code, notes, and snippets.

@JustinMorgan
Last active October 21, 2021 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinMorgan/78b33679b81d031aaa3a0351624c2836 to your computer and use it in GitHub Desktop.
Save JustinMorgan/78b33679b81d031aaa3a0351624c2836 to your computer and use it in GitHub Desktop.
Set-once static and instance value in subclasses / Requiring a static member / Specifying a static member in an interface
abstract class Widget {
abstract readonly widgetType: string;
public display: { [key: string]: string; };
constructor(data?: any) {
this.display = {
a: 'a' in data ? data.a : 'a-parentClass',
b: 'b' in data ? data.b : 'b-parentClass',
c: 'c' in data ? data.c : 'c-parentClass'
};
}
}
interface IWidget {
constructor: Function & {
readonly widgetType?: string;
}
}
function WidgetSubClass(widgetType: string) {
return class extends Widget implements IWidget {
readonly widgetType: string = widgetType;
static readonly widgetType: string = widgetType;
constructor(data?: any) {
super(data);
Object.assign(this.display, {
c: 'c' in data ? data.c : 'c-subClass'
});
}
}
}
class SubClass extends WidgetSubClass('test-widgetType') {
}
const sc = new SubClass({a: 'a-instance'})
console.clear()
console.log(sc.display)
console.log(sc.widgetType)
console.log((sc as IWidget).constructor.widgetType)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment