开启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
相关产品推荐
相关产品推荐

