Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  176] [ 6]  / answers: 1 / hits: 31195  / 8 Years ago, mon, june 6, 2016, 12:00:00

I have an app that initializes by running its method .init(params) like this:



app.init([TopBar, StatusBar, MainArea]);


Where TopBar, StatusBar and MainArea are classes, not instances of classes. Each of these classes implements the same interface IComponent.



I want to instantiate objects from the passed classes in the .init(params) method, like this:



init(params: IComponent[]): void {
params.map(function (component) {
let comp = new component();
this.components[comp.constructor.name] = comp;
}, this);


The issue is that as these are not instance, TypeScript doesn't know their types and throws an error:




error TS2345: Argument of type '(typeof TopBar | typeof StatusBar |
typeof MainArea)[]' is not assignable to parameter of type
'IComponent[]'.




How do I fix the code so that I could pass an array of classes that implement some interface to a method?


More From » typescript

 Answers
29

There is a working typescript playground (run it to get alert with result)



what we need is to create a custom type InterfaceComponent. That will be expected as an array of the init() method



interface IComponent { }
class TopBar implements IComponent { }
class StatusBar implements IComponent { }
class MainArea implements IComponent { }

// this is a type we want to be passed into INIT as an array
type InterfaceComponent = (typeof TopBar | typeof StatusBar | typeof MainArea);

class MyClass {

components: {[key:string] : IComponent } = {};

init(params: (InterfaceComponent)[]): void {
params.map((component) => {
let comp = new component();
this.components[comp.constructor[name]] = comp;
}, this);
}
}

let x = new MyClass();
x.init([TopBar, StatusBar, MainArea])

alert(JSON.stringify(x.components))


Check it here


[#61893] Thursday, June 2, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;