0

I tried to instantiate dynamically my class in a Vue JS with TypeScript project.

I tried this solution.

It works in Angular 2+ but in my Vue project I have this error :

Uncaught TypeError: Object prototype may only be an Object or null: undefined

I have a Classes.ts file

import {CMyClass} from 'path/to/my/class';
export const Classes = {
     CMyClass: CMyClass
}

My class file :

import {CMyOtherClass} from 'path/to/my/mother/class';
export class CMyClass extends CMyOtherClass {
     constructor() {}
}

My mother class file :

export class CMyOtherClass {
    constructor() {}
}

And my function to instantiate a class :

import {Classes} from 'path/to/Classes/constante';
buildClass(className: string): any {
     return new Classes[className]();
}

An idea ?

V. Pivet
  • 1,320
  • 3
  • 25
  • 57
  • `Classes.ts` should maybe be `export const Classes = {` (With an `=`) since you're exporting an object? – Quangdao Nguyen Jul 16 '19 at 13:13
  • @QuangdaoNguyen I don't understand what do you mean ? – V. Pivet Jul 16 '19 at 13:15
  • In `Classes.ts` you have `export const Classes { ... }` which is exporting an undefined constant `Classes`, and then creating an unnamed object `{ CMyClass: CMyClass }` as a separate statement (imagine that there's a semicolon after `export const Classes`). What you want is an equals sign `=` to assign the value of the object to a new constant `Classes`, ie `export const Classes = {`. See here: http://www.typescriptlang.org/play/#code/FAUwHgDg9gTgLgAgMZQHYGdEGEA2BDddEdBAb2AUsqwFkBPXA9ALgVof0OAF9g-xo8ZGkxtOREgF4yFKm3qNCrdovQ8gA – Quangdao Nguyen Jul 16 '19 at 13:23
  • @QuangdaoNguyen Oh sure, I did a mistake when I write my question. I have an "=" in my code. But It doesn't works. I edited my post. – V. Pivet Jul 16 '19 at 13:25
  • 2
    That error sounds like `CMyOtherClass` does not have a prototype. Or which line exactly throws the exception? – Bergi Jul 16 '19 at 13:30
  • @Bergi I think to, when I remove the extends it works. But I don't know I have to do to keep the parent class. Have you got an idea ? – V. Pivet Jul 16 '19 at 13:31
  • @V.Pivet Where does `CMyOtherClass` come from? Please post the code related to it. – Bergi Jul 16 '19 at 13:33
  • @Bergi I edited my post. I hope this can help. – V. Pivet Jul 16 '19 at 13:38
  • @V.Pivet Looks normal. Any circular dependencies? – Bergi Jul 16 '19 at 14:06
  • @Bergi hum no ... – V. Pivet Jul 16 '19 at 14:07

0 Answers0