How to infer the constant array type from its content?

Viewed 142

If I define the following array:

const array = ['a', 'b', 'c'];

Its type will be string[]. How to infer the type from its content, to avoid the necessity to repeat array content in the type definition of array? I.e. this:

const array: ['a', 'b', 'c'] = ['a', 'b', 'c'];
1 Answers

I found the simplest solution: const assertion.

const array = ['a', 'b', 'c'] as const;

The detailed explanation are here.

Related