You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript中如何校验函数参数是否为指定的自定义类型数组

问题解答

TypeScript 属于静态类型语言,所有接口、类型定义仅在编译阶段做类型检查,运行时会被完全擦除,因此无法直接用 typeof 操作符判断自定义的复合类型。你需要手动编写运行时校验逻辑,配合类型守卫实现需求。

实现步骤

  • 第一步:编写单条数据的类型守卫函数,判断单个对象是否符合 replacementMap 结构
  • 第二步:校验参数 m 首先是数组类型,再遍历校验数组内所有元素都符合 replacementMap 结构
  • 额外修正原代码两处问题:1. forEach 回调中误写的m.value应为v.value;2. 入参 t 校验失败时的返回值与声明的string|null返回类型不匹配,统一返回 null

完整可运行代码

interface replacementMap {
  key: string,
  value: string
}

type templateString = string

// 类型守卫:判断入参是否为合法的 replacementMap 类型
const isReplacementMap = (item: unknown): item is replacementMap => {
  return typeof item === 'object' 
    && item !== null 
    && 'key' in item 
    && 'value' in item
    && typeof (item as replacementMap).key === 'string'
    && typeof (item as replacementMap).value === 'string'
}

const replaceStringsInTemplate = (m: Array<replacementMap>, t: templateString): string | null => {
  // 校验模板字符串
  if (typeof t !== 'string') return null
  // 校验 replacement 数组
  if (!Array.isArray(m) || !m.every(isReplacementMap)) return null
  
  let rtn = t;
  m.forEach((v) => {
    rtn = rtn.split(v.key).join(v.value)
  })
  return rtn;
}

补充说明

如果你的项目对校验逻辑的复用性、复杂度要求更高,也可以引入 Zod、Yup 等 Schema 校验库,通过定义 Schema 同时生成 TS 类型和运行时校验逻辑,避免手动编写类型守卫的重复工作。

内容的提问来源于stack exchange,提问作者Gilberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:54:03