vicg
vicg

Reputation: 1368

How to type narrow a string into a discriminating union using an array?

For example, let's say I have the following type and I have a string I want to narrow into a LexemeType

export const LexemeType = ['(', ')', '{', '}', ',', '.', '-', '+', ';', '*'] as const;

export type LexemeType = typeof LexemeType[number];

Why doesn't the following work?

if (str in LexemeType) {
  // use str as LexemeType
}

Upvotes: 1

Views: 51

Answers (1)

Nadia Chibrikova
Nadia Chibrikova

Reputation: 5036

The in operator checks the object's property keys, not their values. If you have say {colour:'red'} object in will return true for 'colour' but false for 'red'. In case of array properties are indexes, so 3 in LexemeType will return true, but not '}' in LexemeType, which will be false. What you need is LexemeType.includes(str)

Upvotes: 3

Related Questions