TypeScript类型参数问号语法的官方名称及文档查询
TypeScript泛型类类型不兼容问题与通配符特性解析
代码场景
abstract class Component<P, S> { state?: Readonly<S>; props?: P; } interface IModuleProperties { name: string; } interface IModuleState { index: number; } export class ModuleBase<P extends IModuleProperties, S extends IModuleState> extends Component<P, S> { } export class Module1 extends ModuleBase<IModuleProperties, IModuleState> { } const t: typeof ModuleBase = Module1; // 类型错误 const t2: typeof ModuleBase<?,?> = Module1; // 编译通过(TS 4.9.3+)
错误提示
Type 'typeof Module1' is not assignable to type 'typeof ModuleBase'. Construct signature return types 'Module1' and 'ModuleBase<P, S>' are incompatible. The types of 'state' are incompatible between these types. Type 'Readonly<IModuleState> | undefined' is not assignable to type 'Readonly<S> | undefined'. Type 'Readonly<IModuleState>' is not assignable to type 'Readonly<S>'.(2322)
错误原因
typeof ModuleBase对应的是未绑定泛型参数的类构造函数类型,它可以接受任意满足约束的P和S,返回对应的ModuleBase<P, S>实例。但Module1是已经固定了P=IModuleProperties、S=IModuleState的子类构造函数,只能生成Module1类型的实例,无法适配“任意泛型参数的ModuleBase构造函数”,因此类型检查失败。
<?,?>特性说明
你用到的typeof ModuleBase<?,?>是TypeScript 4.9新增的泛型查询通配符(Wildcard Types in Type Queries),属于存在类型的简化语法。它表示“ModuleBase绑定了某一组符合约束的具体类型参数后的构造函数类型”,不需要明确写出具体参数,TypeScript会自动推断出匹配的类型。
该特性的官方说明可在TypeScript 4.9的发布文档中找到,对应的章节是Wildcard Types in Type Queries。
正确写法
直接指定ModuleBase绑定的具体类型参数,替代通配符:
const t2: typeof ModuleBase<IModuleProperties, IModuleState> = Module1;
内容的提问来源于stack exchange,提问作者Mike Lischke
相关产品推荐
相关产品推荐

