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

开启Strict模式后,TypeScript为何不对response.json()返回的any类型报错?

问题解析

为什么data的any类型没有报错?

Strict模式中的noImplicitAny规则,仅针对隐式推断产生的any——也就是当TypeScript无法自动推导变量类型,且你未手动指定类型注解时,才会触发错误。但response.json()的返回类型是TypeScript内置类型定义里显式声明的Promise<any>,属于合法的显式any,Strict模式不会对这类情况报错。

简单来说:这个any是官方类型定义主动设定的,不是TypeScript无法推断类型才 fallback 到的any,所以不在Strict模式的报错范围内。

为什么any传给接受Movie[]的函数没报错?

TypeScript里的any类型是专门设计的“类型逃逸舱”,它可以和任何类型双向兼容:any值可以赋值给任意类型,任意类型的值也能赋值给any。因此当你把data.results(any类型)传给仅接受Movie[]的setMovieList时,TypeScript会直接跳过类型检查,不会抛出错误。

示例代码

const response = await fetch(endpoint);

//type of 'data' is 'any', with no errors shown.
const data = await response.json();

//This function only accepts the type 'Movie[]', but no errors are shown when 'any' is passed.
setMovieList(data.results);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:18:17