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

TypeScript泛型默认值推断异常求助:预期类型未正确推导

TypeScript泛型推断异常问题排查

我在TypeScript中遇到了泛型推断的异常行为:

  • 当为Compositor<CT extends ComponentType[]=[]>的泛型参数设置默认空数组时
  • TypeScript始终为SystemWithRule类型推断出ComponentType[],而非预期的[]

这令我困惑,期望得到帮助:

  • 预期this.rules的类型被推断为[typeof ComponentA]
  • 而非实际得到的[ComponentType<Component> | typeof ComponentA]

我无法找到ComponentType<Component>的推断来源,明明泛型默认值是空数组[]。相关代码如下:

type Constructor<T> = new ( ...args: never ) => T;
type ComponentType<T extends Component=Component> = Constructor<T>
abstract class Component {
    declare _: never;
    declare constructorType: ComponentType<this>;
}

export type SystemWithRule<T, C extends ComponentType[]> = T extends Constructor<System<infer CC>>
    ? [ ...CC, ...C ]
    : never;

abstract class System<R extends ComponentType[]=[]> {
    static behavior( behaviors?:'update'|'dirty'|'input'|'none' ) {
        return class Compositor<CT extends ComponentType[]=[]> extends System<CT> {
            static hasAny<C extends ComponentType[], T>( this:T, components:C ) {
                return class extends Compositor< SystemWithRule<T, C> > {
                    static override hasAny:never;
                };
            }

            static hasAll<C extends ComponentType[], T>( this:T, components:C ) {
                return class extends Compositor< SystemWithRule<T, C> > {
                    static override hasAll:never;
                };
            }

            static hasMaybe<C extends ComponentType[], T>( this:T, components:C ) {
                return class extends Compositor< SystemWithRule<T, C> > {
                    static override hasMaybe:never;
                };
            }
        };
    }

    declare rules: R;
}

class ComponentA extends Component {
    declare private __: never;
}
class ComponentB extends Component {
    declare private __: never;
}

export class SystemA extends System
    .behavior( 'update' )
    .hasAny([
        ComponentA,
    ])
{
    update() {
        this.rules;
    }
}

在线演示:TypeScript Playground
简化版演示:TypeScript Playground

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:37:32