Ask Your Question
2

How can the generic type of a const variable with inferred type be narrowed down in Typescript?

asked 2023-06-08 15:01:45 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-08 15:13:02 +0000

devzero gravatar image

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>
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-08 15:01:45 +0000

Seen: 18 times

Last updated: Jun 08 '23