Zulfe
Zulfe

Reputation: 881

Is it possible to use the name of a Typescript interface as a key in a generic type?

I would like to create a generic type that uses the name of the type parameter as a key in the resultant type. There is no need for such a type to exist in the transpiled JavaScript. It only needs to work for the purpose of type enforcement for the TypeScript source.

I first tried something like this...

export type Wrapped<T> = {
    `${T}`: T;
};

...and this...

export type Wrapped<T> = {
    [nameof T]: T;
};

but these aren't valid.

For example...

interface MyInterface {
    text: string;
}

const instance: MyInterface = { 'text': 'Hello!' };
const wrappedInstance: Wrapped<MyInterface> = { 'MyInterface': { 'text': 'World!' } };

Is TypeScript capable of creating such a type?

Upvotes: 0

Views: 480

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

This is simply not possible on the current version of Typescript (4.6). The name of a type simply cannot be used as a type of any sort.

Whatever you are doing, you'll need to find another way.

Upvotes: 1

Related Questions