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

如何让TypeScript泛型根据映射对象匹配类构造函数并返回对应参数类型?

问题描述

需要实现一个动态TypeScript泛型类型ConstructorParams,原硬编码版本逻辑如下:当泛型参数T匹配typeof Text时返回TextOptions,否则返回类构造函数的第一个参数(仅当T是类构造函数时)。原代码:

import type {
  Text,
  TextOptions,
} from 'pixi.js'

export type ConstructorParams<T extends abstract new (...args: any) => any> =
  T extends typeof Text
    ? TextOptions
    : T extends new (...args: infer A) => any
      ? A[0]
      : never;

为了支持多类型匹配且避免大量独立条件判断,尝试用映射对象重构,但代码无法正常工作:

import type {
  BlurFilter,
  BlurFilterOptions,
  Text,
  TextOptions,
} from 'pixi.js'

type ConstructorOverrides = {
  BlurFilter: BlurFilterOptions
  Text: TextOptions
}

export type ConstructorParams<T extends abstract new (...args: any) => any> =
  T extends keyof ConstructorOverrides
    ? ConstructorOverrides[T]
    : T extends new (...args: infer A) => any
      ? A[0]
      : never;

问题根源:当前代码检查T是否匹配ConstructorOverrides的字符串键,但实际需要检查T对应的类构造函数是否存在于映射中。

解决方案

核心修改点是调整ConstructorOverrides的键类型,从类名字符串改为类构造函数类型,这样才能和泛型参数T的类型匹配。具体实现如下:

import type {
  BlurFilter,
  BlurFilterOptions,
  Text,
  TextOptions,
} from 'pixi.js'

// 用构造函数类型作为键,对应值为要返回的Options类型
type ConstructorOverrides = {
  [typeof Text]: TextOptions;
  [typeof BlurFilter]: BlurFilterOptions;
}

export type ConstructorParams<T extends abstract new (...args: any) => any> =
  // 现在T可以匹配映射中的构造函数类型键
  T extends keyof ConstructorOverrides
    ? ConstructorOverrides[T]
    : T extends new (...args: infer A) => any
      ? A[0]
      : never;

逻辑说明

  1. 映射对象调整:将ConstructorOverrides的键从字符串"Text"/"BlurFilter"改为typeof Text/typeof BlurFilter(即类的构造函数类型),这样泛型参数T(构造函数类型)才能和键类型匹配。
  2. 类型匹配逻辑:当T是映射中存在的构造函数类型时,直接返回对应的Options类型;否则通过类型推断提取构造函数的第一个参数类型。

这样既实现了多类型的动态匹配,又保持了原类型的核心逻辑,无需编写大量独立条件分支。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:26:16