0

I have a file with a lot of constant variables in it:

// foo.ts
export const FOO = 'foo';
export const BAR = 'bar';

I want to be able to declare a type that enforces that a value is one of those constants:

// fooTypes.ts
import * as consts from './foo';

const fooObjects = Object.values(consts);  // I don't want to declare this variable
export type FooConst = fooObjects[number]; // type ActivityType = "foo" | "bar"

This does what I want, FooConsts contains a union of all of the values from foo.ts, but I don't want to have to declare additional variables that will end up in my run-time/bundle. This is just for type checking.

// useFooTypes.ts
import { FooConst } from './fooTypes'

type FooHolder {
  value: FooConst;
}

Also, I don't want to repeat all those declarations in a union type.

I tried doing this in a declaration file, but alas, Statements are not allowed in ambient contexts.ts(1036)

kvanost
  • 11
  • 2

1 Answers1

1

I ended up switching my implementation to use enum.

// foo.js
export type Foo = keyof typeof foo;

export enum foo {
  FOO = 'foo',
  BAR = 'bar'
}

kvanost
  • 11
  • 2