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

TypeScript:命名参数传递断言函数调用报错,位置参数为何正常?

问题解答

这不是你的写法错误,而是TypeScript当前的设计限制。

TypeScript对断言函数的调用有严格校验规则:要求调用目标必须是带有显式类型注解的标识符。当你通过对象解构获取myAssertionFunc时,虽然你给整个参数对象指定了类型,但解构后的变量本身没有单独的显式类型注解,TypeScript无法直接确认它的断言函数类型,因此触发了ts(2775)错误。而位置参数的情况中,参数本身带有显式的断言函数类型注解,符合校验规则,所以能正常运行。

解决办法

给解构后的变量添加显式类型注解,让TypeScript明确它的断言函数身份:

const myFunc = ({ myAssertionFunc }: { myAssertionFunc: (x: unknown) => asserts x is string }) => {
  // 给解构后的变量添加显式类型注解
  const assertFunc: (x: unknown) => asserts x is string = myAssertionFunc;
  assertFunc(1234); // 不再报错
};

或者通过类型断言快速绕过校验(适合场景简单的情况):

const myFunc = ({ myAssertionFunc }: { myAssertionFunc: (x: unknown) => asserts x is string }) => {
  (myAssertionFunc as (x: unknown) => asserts x is string)(1234);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 17:01:04