1

I have a function. It should accept class definitions and produce object with their names (first letter - lowercase) mapped to their instances. I want it to be strongly typed.

function createObject (...classes: any[]) {
    // something like
    return classes.reduce((acc, class) => {
        const name = class.name.charAt(0).toLowerCase() + class.name.slice(1);
        acc[name] = new class();
        return acc;
    });
}

So I want to use it like:

const { aClass, bClass, cClass } = createObject(AClass, BClass, CClass);

UPDATE

I'm trying to extract class name like this:

type GetName<T> = 'name' extends keyof T ? T['name'] : never;
type ClassName = GetName<AClass>;

But ClassName is never. Guess I'm missing something crucial.

Kindzoku
  • 1,368
  • 1
  • 10
  • 29
  • TypeScript doesn't know that `AClass.name` is `"AClass"`, and without support for a `nameof` type operator as requested in [ms/TS#1579](https://github.com/microsoft/TypeScript/issues/1579) it can't know this. If you try a "fixed" version of your code (e.g., `GetName` you'll see that it's `string`, which isn't helpful to you, right?. If you want the compiler to know that `AClass.name` is `"AClass"` you'll have to add that information explicitly, at which point you should probably change the approach entirely. See the answer to the linked question for more information. – jcalz Mar 22 '23 at 14:03
  • Yeah. Thx. In the end I finished up with array implementation. – Kindzoku Mar 23 '23 at 15:30

0 Answers0