1

We have:

type test = {
  id: number;
  name: string;
};

const arr: test[] = [{ id: 1, name: 'test-1' }, { id: 2, name: 'test-2' }];

And I want to create a type from an array of objects:

type other = typeof arr[number]['name'];

const another: other = 'test-1'; // Should be 'test-1' | 'test-2' but it's string

If I remove the custom type of arr and use const assertion:

const arr = [{ id: 1, name: 'test-1' }, { id: 2, name: 'test-2' }] as const;

type other = typeof arr[number]['name'];

const another: other = 'test-2'; // Works!

It'll work, but I want to have a type for my arr too.

How can I create something like this:

type test = {
  id: number;
  name: string;
};

const arr: test[] = [
  { id: 1, name: 'test-1' },
  { id: 2, name: 'test-2' }
] as const;

type other = typeof arr[number]['name'];

const another: other = 'test-1';

I tried to use ReadonlyArray<test> but no luck!

MohamadKh75
  • 2,582
  • 5
  • 28
  • 54
  • Do you want `other` to be `'test-1' | 'test-2'` or `string`? Do you want `arr` to contain only those two elements, or to contain any objects of type `test` with arbitrary `string` names? – Bergi May 15 '22 at 22:27
  • @Bergi I want `other` to be `test-1' | 'test-2` and want `arr` to only contain those two elements. – MohamadKh75 May 15 '22 at 22:33
  • 1
    Then you should just use `as const`, and not declare `arr: test[]`. It's not clear what you mean by "*I want to have a type for my `arr` too.*", or *why* you'd want that. The `arr` variable always has a type. – Bergi May 15 '22 at 22:45
  • I want to have type for my `arr`, how can I do that? – MohamadKh75 May 15 '22 at 22:46
  • [This](https://stackoverflow.com/a/66993654/12162258) answer might be useful in understanding why `as const` accomplishes what you want. – thisisrandy May 15 '22 at 22:50
  • So there is no way to declare type for my `arr`? – MohamadKh75 May 15 '22 at 22:53
  • Can you articulate *why* you want to declare the type of `arr`? What is the use case driving the question? You shouldn't need to do it, and if you do it, it will be like [this](https://tsplay.dev/N7OMRN), which is going to be annoying. So people are asking you *why* you think you need this. – jcalz May 16 '22 at 01:21

0 Answers0