Search code examples
typescriptinterfacetypecheckingtypeguards

How can I check a parameter type in Typescript?


How can I check inside a function if a correctly typed object was provided as a parameter? Check out my sample code

interface replacementMap {
  key: string,
  value: string
} // ex [{key: '[last]', value: 'Washington'}, {key: '[first]', value: 'George'}]

type templateString = string // ex `[last], [first]`

const replaceStringsInTemplate = (m: Array<replacementMap>, t: templateString): (string | null) => {
  // String is easy to check
  if (typeof t !== 'string') return
  // But how would I do a check like this?
  if (typeof m !== 'replacementMap[]') return null
  
  let rtn = t;

  m.forEach((v) => {
    rtn = rtn.split(v.key).join(m.value)
  }
  return rtn;
}

In the above code, how can I check that the parameter m is actually of type Array<replacementMap>?


Solution

  • First, in most cases you won't need to do a runtime check. Typescript's goal is to catch these kind of things at compile time, so if you're using typescript well, then your checks shouldn't be able to fail.

    But perhaps you're making a library for other people to use, and they might not use typescript or might call your code in unexpected ways and you just want to be sure. In that case, here are some options. To check if something is an array, javascript provides us with this method:

    if (Array.isArray(m)) {
    

    And if you want to check the contents of the array, you can do something like this:

    if (Array.isArray(m) && m[0] && typeof m[0] === 'object' && "key" in m[0] && "value" in m[0]) {
    

    That's just an example; i don't know what cases you're trying to guard against, so you might check for more things or less things, depending on what your goal is.