When handling a search parameter in the URL, such as ?mode=view
, it is important to validate the value of mode
to ensure it is either 'edit' or 'view'. To achieve this, a custom type called ModeTuple
is created and converted to a union type using indexed access types ModeTuple[number]
.
type ModeTuple = ['view', 'edit'];
const searchParams = new URLSearchParams();
const modes: ModeTuple = ['view', 'edit'];
const m1: ModeTuple[number] = modes.includes(searchParams.get('mode')) ? searchParams.get('mode') : 'view';
The goal is to verify if the value of mode
is valid by using modes.includes(...)
, which should narrow the type down to 'edit' | 'view'
.
An error occurs:
Argument of type 'string' is not assignable to parameter of type '"view" | "edit"'
This suggests that the Array.prototype.includes
method may not successfully narrow the type from string
to
"view" | "edit"
. Despite the logic in the JavaScript code dictating that the mode
value must be either 'view' or 'edit', TypeScript does not recognize this.