0

This is a follow up question for TypeScript map function to change property type.

If I have the following

class A {  }
class B {  }
var var1 = [{ path: "aa", comp: "A" }, { path: "b", comp: "B" }];

Is there a way to programmatically generate a mapping object like this

var nameToClassMapping = {
    A: A,
    B: B
};

rather than hardcode it?

1 Answer 1

1

You can use a decorator to do that:

var nameToClassMapping = {};

function myDecorator(target: any) {
    nameToClassMapping[target.name] = target;
}

@myDecorator
class A { }

I haven't tested it, but it should work, or at least give you a way.

Sign up to request clarification or add additional context in comments.

3 Comments

so the @myDecorator is used each class A and B? what is the scope if nameToClassMapping? Can you explain a bit? Thanks,
Yes, you need to use this decorator before every class you want to be able to map to. The decorator is just a function that is executed and it receives the class after it as parameter. The link in my question to the official documentation is a good place to start.
Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.