WordPress块开发TypeScript中useSelect类型错误排查
解决TypeScript中useSelect调用core/editor时的类型错误
问题出在TypeScript无法自动推断select('core/editor')返回的类型,默认将其判定为never,导致调用getCurrentPostType()时触发类型报错。以下是几种实现类型安全的解决思路:
方法1:使用官方类型断言
WordPress的@wordpress/editor包自带类型定义,直接导入后对store进行类型断言即可:
import { useSelect } from '@wordpress/data'; import type { EditorStore } from '@wordpress/editor'; const postType = useSelect( ( select ) => ( select( 'core/editor' ) as EditorStore ).getCurrentPostType(), [] );
方法2:自定义类型声明
如果官方类型缺失或不符合需求,可以自行定义需要的接口:
import { useSelect } from '@wordpress/data'; // 定义core/editor store的必要方法类型 interface EditorSelectStore { getCurrentPostType(): string; // 可按需添加其他你需要调用的方法 } const postType = useSelect( ( select ) => ( select( 'core/editor' ) as EditorSelectStore ).getCurrentPostType(), [] );
方法3:扩展@wordpress/data的StoreMap(推荐)
通过模块扩展让TypeScript全局识别core/editor的store类型,后续无需重复断言:
import { useSelect } from '@wordpress/data'; import type { EditorStore } from '@wordpress/editor'; // 扩展@wordpress/data的StoreMap接口,关联core/editor和对应类型 declare module '@wordpress/data' { interface StoreMap { 'core/editor': EditorStore; } } // 现在直接调用就会自动识别类型,无报错 const postType = useSelect( ( select ) => select( 'core/editor' ).getCurrentPostType(), [] );
原理说明
@wordpress/data的select函数对于未在StoreMap中注册的store key,默认返回never类型。通过上述方式,我们明确告知TypeScriptcore/editor store的结构,从而实现类型检查和自动补全。
内容的提问来源于stack exchange,提问作者codewithfeeling
相关产品推荐
相关产品推荐

