Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make typescript take filtering on data type into account

I have these interfaces:

interface ParsedUrlQuery {
  [key: string]: string | string[]
}

interface URLParams {
  [key: string]: string
}

I then write the function:

const getParamsFromQuery = (query: ParsedUrlQuery): URLParams => {
  return Object.fromEntries(
    Object.entries(query).filter(([_key, value]) => typeof value === 'string')
  )
}

I get a typescript error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type '{ [k: string]: string | string[]; }' is not assignable to type 'URLParams'.
  'string' index signatures are incompatible.
    Type 'string | string[]' is not assignable to type 'string'.
      Type 'string[]' is not assignable to type 'string'.ts(2322)

Why does this not work and what do I need to make typescript take into account this filter action?

>Solution :

You are looking for a typeguard which lets you tell typescript that if your function returns true – then value is string.

const getParamsFromQuery = (query: ParsedUrlQuery): URLParams => {
  return Object.fromEntries(
    Object.entries(query).filter((kv): kv is [string, string] => typeof kv[1] === 'string')
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading