Open3

TSでEnumがユニオンを満たしているか保証する

Nakano as a ServiceNakano as a Service
type ExpectedFooBar = 'Foo' | 'Bar';

const FooBar = {
  Foo: 'Foo',
  Bar: 'Bar',
} as const;

// これがExcectedFooBarを満たしていることを保証したい
type FooBar = (typeof FooBar)[keyof typeof FooBar];
Nakano as a ServiceNakano as a Service
type ExpectedFooBar = 'Foo' | 'Bar';

const FooBar = {
  Foo: 'Foo',
  Bar: 'Bar',
} as const satisfies {
  [key in ExpectedFooBar]: key;
};

type FooBar = (typeof FooBar)[keyof typeof FooBar];

ただしKeyとValueは等しくなければならない。

Nakano as a ServiceNakano as a Service
enum ExpectedFooBar {
  Foooo = 'Foo',
  Bar = 'Bar',
}

const FooBar = {
  Foooo: 'Foo',
  Bar: 'Bar',
} as const satisfies {
  [key in keyof typeof ExpectedFooBar]: `${(typeof ExpectedFooBar)[key]}`;
};

type FooBar = (typeof FooBar)[keyof typeof FooBar];