1

Here is what I'm trying to achieve

function Enum<T extends string>(arr: T[]): Record<T, T> {
  return arr.reduce((next, key, index) => {
    next[key] = key
    return next
  }, {} as Record<T, T>)
}
const Codes = Enum([
  'foo',
  'bar'
])

I want typescript to know that Codes.foo is only 'foo'. Right now it thinks it can be 'foo' | 'bar'

I'm aware of Enums. This is more of curiosity question.

1 Answer 1

1

You should use { [K in T]: K } instead of Record<T, T> to tell typescript that the key is actually the value:

function Enum<T extends string>(o: T[])  {
  return o.reduce((next, key) => {
    next[key] = key;
    return next;
  }, {} as {[K in T]: K});
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.