如何检查 Typescript 中的参数类型?

How can I check a parameter type in Typescript?

如果提供了正确类型的对象作为参数,我如何检查函数内部?查看我的示例代码

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;
}

在上面的代码中,如何检查参数m实际上是Array<replacementMap>类型?

首先,在大多数情况下,您不需要进行运行时检查。 Typescript 的目标是在编译时捕获这些东西,所以如果你使用好 typescript,那么你的检查应该不会失败。

但也许您正在制作一个供其他人使用的库,而他们可能不使用打字稿或可能以意想不到的方式调用您的代码,而您只是想确定一下。在这种情况下,这里有一些选择。为了检查某物是否是数组,javascript 为我们提供了这个方法:

if (Array.isArray(m)) {

如果你想检查数组的内容,你可以这样做:

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

这只是一个例子;我不知道你要防止什么情况,所以你可能会检查更多或更少的东西,这取决于你的目标是什么。