指定非any类型仍触发'Unsafe call of an any typed value' lint错误求助
解决Gatsby中createPage的'Unsafe call of an
any typed value' lint错误 问题场景
我在gatsby-node.ts中写了这段分页代码:
interface IPage { path: string; component: typeof BlogTemplate | typeof PostTemplate; context: { slug?: string; limit: number; skip: number; isFirstPage: boolean; isLastPage: boolean; currentPage: number; totalPages: number; }; } Array.from({ length: totalPages }).forEach((_, index) => { const currentPage = index + 1; const isFirstPage = index === 0; const isLastPage = currentPage === totalPages; createPage({ path: isFirstPage ? '/blog' : `/blog/${currentPage}`, component: BlogTemplate, context: { limit: postsPerPage, skip: index * postsPerPage, isFirstPage, isLastPage, currentPage, totalPages, }, } as IPage); });
但lint报错指向createPage调用:'Unsafe call of an any typed value',明明已经定义了IPage类型,问题出在哪?
问题根源
不是你自定义的IPage类型有问题,而是TypeScript无法识别createPage函数的类型,把它推断成了any。你用as IPage做类型断言只是强制给参数套了自定义类型,但没让TS知道这个参数符合createPage要求的官方类型约束。此时调用一个被推断为any的函数,就会触发这个lint规则。
解决办法
1. 直接用Gatsby官方类型(推荐)
Gatsby为node API提供了完整的TypeScript类型,直接用官方的CreatePageArgs替代自定义的IPage即可:
import { CreatePageArgs } from "gatsby"; // 省略其他逻辑代码 Array.from({ length: totalPages }).forEach((_, index) => { const currentPage = index + 1; const isFirstPage = index === 0; const isLastPage = currentPage === totalPages; const pageData: CreatePageArgs = { path: isFirstPage ? '/blog' : `/blog/${currentPage}`, component: BlogTemplate, context: { limit: postsPerPage, skip: index * postsPerPage, isFirstPage, isLastPage, currentPage, totalPages, }, }; createPage(pageData); });
2. 确保Gatsby全局类型被正确加载
如果还是报错,检查你的项目配置:
- Gatsby v4及以上版本内置了类型,无需额外安装
@types/gatsby;如果是旧版本,先执行npm install @types/gatsby --save-dev - 在
tsconfig.json的compilerOptions.types中添加gatsby:
{ "compilerOptions": { "types": ["gatsby"] } }
3. 手动为createPage指定类型(备选)
如果上述方法无效,可以手动给createPage添加类型约束:
import { PageComponent } from "gatsby"; // 定义createPage的类型 type CreatePageFn = (args: { path: string; component: PageComponent; context: { slug?: string; limit: number; skip: number; isFirstPage: boolean; isLastPage: boolean; currentPage: number; totalPages: number; }; }) => void; // 断言createPage的类型 const createPage = actions.createPage as CreatePageFn;
内容的提问来源于stack exchange,提问作者mkelley33
相关产品推荐
相关产品推荐

