1 | initial version |
In Typescript, the generic type of a const variable with inferred type can be narrowed down using the as
keyword or the is
type guard.
For example, suppose we have a const variable arr
with inferred type Array<number | string>
:
const arr = [1, "two", 3, "four"] // inferred type: Array<number | string>
We can narrow down the generic type to Array<string>
using the as
keyword:
const stringArr = arr.filter((val) => typeof val === "string") as Array<string>
Alternatively, we can use the is
type guard to narrow down the generic type:
function isString(val: any): val is string {
return typeof val === "string"
}
const stringArr = arr.filter(isString) // inferred type: Array<string>