Ask Your Question
1

How can the string literal type in an array be determined without using 'as const'?

asked 2023-04-02 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-02-27 17:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-02 11:00:00 +0000

Seen: 8 times

Last updated: Feb 27 '22