Generate a type from a module's own exported keys

1.2k Views Asked by At

Given a module like this:

export const a: string;
export const b: string;

From outside you can generate a type "a" | "b" like this:

import * as stuff from "./stuff";
type StuffKeys = keyof typeof stuff; // "a" | "b"

But I want to generate and export this type from within the module. Something like:

export type MyKeys = keyof typeof this;

But that does not work.

Is there a way to do this?

1

There are 1 best solutions below

1
On BEST ANSWER

I did not believe, that what you are planning to do was possible, as the line export type MyKeys... would have neede to be included in the keys type itself.

However, surprisingly it is working to just import the module into itself and exporting the keys from there.

main.ts

export const a : string = 'a';
export const b : string = 'b';

import * as main from './main'
export type MyKeys = keyof typeof main;

test.ts

import {MyKeys} from './main';

const a : MyKeys = 'a';
const b : MyKeys = 'c'; // TS2322: Type '"c"' is not assignable to type '"a" | "b"'.