'How to narrow the type of the value returned by URLSearchParams.get() to union type?
There is a search parameter in URL like this: ?mode=view. The valid value of mode should be 'edit' and 'view', so I create a ModeTuple type for it and convert it to 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';
I want to check if the value of mode is valid using modes.includes(...), then narrow the type to union type 'edit' | 'view'.
Got error:
Argument of type 'string' is not assignable to parameter of type '"view" | "edit"'
It seems Array.prototype.includes method will NOT narrow the type from string to "view" | "edit" successfully. From the logic of the JS code, the mode value must be 'view' or 'edit'. But TSC doesn't know that.
Solution 1:[1]
import .svg, .jpg, .png, .ttf, etc. files like:
ReactDOM.render(
<img src={require("./svg/exmpale.svg")}/>,
document.getElementById('root')
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kareem Adel |
