There are several ways to determine the string literal type in an array without using 'as const':
const fruits: ['apple', 'banana', 'orange'] = ['apple', 'banana', 'orange'];
enum Fruit {
Apple = 'apple',
Banana = 'banana',
Orange = 'orange'
}
const fruits: Fruit[] = [Fruit.Apple, Fruit.Banana, Fruit.Orange];
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.
Asked: 2023-04-02 11:00:00 +0000
Seen: 8 times
Last updated: Feb 27 '22