Last active
October 21, 2021 15:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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