Get keys of namespace and access namespace members with brackets

Viewed 183

How can i import all types from a file without changing it, like the test.ts file below, and access them via the bracket syntax?

test.ts

export type TEST1 = 'test1'
export type TEST2 = 'test2'
export type TEST3 = 'test3'
export type TEST4 = 'test4'

index.ts

import type * as T from './test'

const a: T.TEST1 = 'test1' // what i can do
type B = 'TEST2' | 'TEST3' // subset of available types in test.ts
const b: T[B] = 'test2' // what i want to do

1 Answers

At first glance at the docs it may seem like this is not possible but I think I figured it out. For this specific scenario you've shown in your example where the types are string literals, you could use a combination of an indexable type and a mapped type like this:

test.ts

type TYPES = 'test1' | 'test2' | 'test3' | 'test4';

type MAPPED = {
  [key in TYPES]: TYPES;
}

type TYPE = {
  TEST1: 'test1',
  TEST2: 'test2',
  TEST3: 'test3',
  TEST4: 'test4'
}

type T = MAPPED & TYPE;

export default T;

index.ts

import type T from './test';

type b = 'TEST2' | 'TEST3';
const b: T[b] = 'test1';

The second line will show the error:

Type '"test1"' is not assignable to type '"test2" | "test3"'. Did you mean '"test2"'?

Which proves that this is working as intended.

Related