【问题标题】:How can I check a parameter type in Typescript?如何检查 Typescript 中的参数类型?
【发布时间】:2021-08-29 16:13:32
【问题描述】:

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

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&lt;replacementMap&gt;类型?

【问题讨论】:

    标签: typescript interface typechecking typeguards


    【解决方案1】:

    首先,在大多数情况下,您不需要进行运行时检查。 Typescript 的目标是在编译时捕捉到这些东西,所以如果你很好地使用了 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]) {
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 2012-09-29
      • 1970-01-01
      • 2023-03-17
      • 2021-05-29
      相关资源
      最近更新 更多