Whenever I create an if statement in typescript to check if a variable is either "a"
or "b"
if (str === "a" || str === "b") {
// typescript recognizes that the value can only be "a" or "b"
}
However, this approach can become too verbose, especially when dealing with multiple options.
Is there a more concise way of achieving the same result in typescript? Perhaps something like this:
if (["a", "b"].includes(str)) {
// Unfortunately, typescript cannot infer that it is limited to just "a" or "b"
}
This example may seem oversimplified, but for a more comprehensive scenario, consider identifying if a string corresponds to a boolean property within an interface:
interface Filters {
isPromo?: boolean,
isFreeShipping?: boolean,
isNew?: boolean,
isInStock?: boolean,
title?: string
}
let filters: Filters = {};
for (const filterValuePair of location.search.split("&")) {
const [urlFilter, value] = filterValuePair.split("=");
// In this case, typescript provides no warnings as it deduces the necessity for a boolean property due to the nature of the "if" statement
if (urlFilter === "isPromo" || urlFilter === "isFreeShipping" || urlFilter === "isNew" || urlFilter === "isInStock") {
filters[urlFilter] = Boolean(value);
}
// The following method is briefer but lacks type inference from typescript
if (["isPromo", "isFreeShipping", "isNew", "isInStock"].includes(urlFilter)) {
filters[urlFilter] = Boolean(value);
}
}
Check out the playground here