1
type Item = {
  id: string;
  value: string;
};

const items: Readonly<Item>[] = [
  { id: 'id1', value: 'TODO1' },
  { id: 'id2', value: 'TODO2' },
  { id: 'id3', value: 'TODO3' },
];

I want to get type 'TODO1' | 'TODO2' | 'TODO3';

const items = [...] as const;

type Type = typeof items[number]['value'];

I could get a type by const assertion. But this case, I lost my items type..

1
  • 1
    I don't think you should need the Item type at all - TS will infer it properly. There shouldn't be any issues having a narrow type when a wide one is accepted too. Remove : Readonly<Item>[] and use as const Commented Jun 22, 2021 at 3:41

1 Answer 1

1

You could define the array as const initially, then assign it to items later:

const itemsInitial = [
  { id: 'id1', value: 'TODO1' } as const,
  { id: 'id2', value: 'TODO2' } as const,
  { id: 'id3', value: 'TODO3' } as const,
];
type Type = typeof itemsInitial[number]['value'];
const items: Readonly<Item>[] = itemsInitial;

But you may not need the Item type at all - I don't see a need for it yet, or a need for the Readonly<Item>[] type, given the code in the question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.