How to get a class from a string in TypeScript/JavaScript in an Angular 2 application?
14,701
This sounds like a reflection question in typescript.
Possibly you could check this out if you haven't
Dynamically loading a typescript class (reflection for typescript)
Author by
andreas
Updated on June 25, 2022Comments
-
andreas almost 2 years
In my application, I have something like this:
user.ts
export class User { ... }
and right now, I do this:
app.component.ts
callAnotherFunction(User);
How can I do this if I have the class name as a string, that is
"User"
? If possible, how would I check if the variable really is a usable class?For example:
let test = "User"; if (**test is really a usable class**) { console.log("Yay!"); callAnotherFunction(**something to put here**); } else { console.log("Error!"); }
I am not sure if this is even possible, but thanks for your input already.
All I have found so far is examples like these:
let test = "User"; let user = new window[test]();
But
user
would then be an instance ofUser
. Additionally, it does not seem to work in my Angular 2 application - probably a scope error. If I wanted to try this, what would I need to use instead ofwindow
? -
andreas over 7 yearsYes I have already read this, thank you. The examples work for me, but I would like to get the class instead of the instance. In my example above, for
window["String"]
it works as expected. But as my custom classUser
is not inwindow
, I cannot access it. How could I access it so i can dowindow["User"]
or something similar? -
Nico over 7 yearsdid you also see: stackoverflow.com/a/38127705/1804189 and stackoverflow.com/a/35787628/1804189 They explain how it can be done in Typescript 1.8+
-
andreas over 7 yearsYes, my main problem now seems to be to find out the namespace that
User
lives in. I followed the usual Angular 2 patterns and there you don't explicitely define namespaces. -
Paritosh about 6 years@andreas - were you able to get typescript type from the string using the usual Angular 2 patterns? please provide the any helpful link, I wasn't able to with links provided by Nico