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

TypeScript错误处理函数如何正确定义类型解决Signals类型不匹配报错

错误原因

TS2769报错是因为TypeScript默认将['SIGTERM', 'SIGINT']推断为string[]类型,但process.once和process.kill的信号参数要求是NodeJS.Signals联合类型的成员,普通字符串不能直接赋值给该类型。

解决方法

方案1:显式声明数组类型(最推荐)

直接给errors数组指定NodeJS.Signals[]类型,从根源上限定成员类型符合要求:

async function exitOnError() {
  // 显式指定数组类型为NodeJS.Signals[]
  const errors: NodeJS.Signals[] =  ['SIGTERM', 'SIGINT']
  // 遍历副作用操作使用forEach替代map,语义更匹配
  errors.forEach((type) => {
    process.once(type, async () => {
      try {
        console.log(`Error process.on ${type}`);
        // 若disconnect是方法需要加括号调用,此处根据实际业务调整
        await service.disconnect();
      } finally {
        console.log(`Unexpected error happen on ${type}`);
        process.kill(process.pid, type);
      }
    });
  });
}

方案2:用const断言限定数组字面量类型

如果不想写显式类型声明,可以用as const把数组变成只读字面量类型,TS会自动匹配到Signals类型:

const errors =  ['SIGTERM', 'SIGINT'] as const

方案3:类型守卫实现(兼容动态信号场景)

如果你的信号列表是动态生成的,可以通过类型守卫做 runtime 校验:

function isSignal(type: string): type is NodeJS.Signals {
  return ['SIGTERM', 'SIGINT'].includes(type)
}

// 使用时先做类型校验
errors.forEach((type) => {
  if (isSignal(type)) {
    process.once(type, async () => {
      // 业务逻辑
    })
  }
})

TypeScript 语法规范调整点

  • 遍历数组执行副作用操作不要用map,map设计用来返回新数组,这类场景用forEach更符合语义
  • 异步方法调用要确认是否加执行括号,原代码中await service.disconnect如果是函数类型必须加()才会实际执行
  • 未声明的变量需要补充类型定义,比如示例中的service需要提前定义对应的接口类型,避免隐式any报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:24:02