Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are several ways to determine the string literal type in an array without using 'as const':

  1. Define the array as a tuple with specific string literal types:
const fruits: ['apple', 'banana', 'orange'] = ['apple', 'banana', 'orange'];
  1. Use an enum to define the possible values of the array:
enum Fruit {
  Apple = 'apple',
  Banana = 'banana',
  Orange = 'orange'
}

const fruits: Fruit[] = [Fruit.Apple, Fruit.Banana, Fruit.Orange];
  1. Use a union type to define the possible values of the array:
type Fruit = 'apple' | 'banana' | 'orange';

const fruits: Fruit[] = ['apple', 'banana', 'orange'];

All these methods ensure that the array can only contain the specific string literal types defined and not any other arbitrary string value.