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

如何让TypeScript数组自动适配所有ISlide子类接口?

解决方案

TypeScript 里纯接口方案无法自动收集所有继承自 ISlide 的类型(因为接口是结构类型,编译器不会跟踪继承关系的集合),但可以通过两种方式实现“新增子类型时自动更新数组类型”的需求:

方案一:使用判别式联合 + 类型注册表

给每个子接口添加唯一标识逻辑,再通过注册表自动推导所有子类型的联合类型,新增子类型时只需更新注册表:

import { ComponentType } from 'react';

interface ISlide {
  component: ComponentType;
}

interface ITitleSlide extends ISlide {
  title: string;
  subtitle: string;
}

interface IHeaderSlide extends ISlide {
  header: string;
}

// 注册表:新增子接口时,在这里添加对应类型的占位符
const SlideTypesRegistry = {
  title: {} as ITitleSlide,
  header: {} as IHeaderSlide,
};

// 自动推导所有子类型的联合类型
type AllSlideTypes = typeof SlideTypesRegistry[keyof typeof SlideTypesRegistry];

// 数组直接使用推导后的联合类型,新增子类型无需修改这里
const slides: AllSlideTypes[] = [
  {
    component: TitleSlide,
    title: 'Title',
    subtitle: 'Subtitle'
  },
  {
    component: HeaderSlide,
    header: 'Header'
  }
];

方案二:使用类(名义类型)

类是名义类型,编译器会跟踪类的继承关系,新增子类后只需将实例加入数组,类型会自动推导更新:

import { ComponentType } from 'react';

abstract class Slide {
  constructor(public component: ComponentType) {}
}

class TitleSlide extends Slide {
  constructor(
    component: ComponentType,
    public title: string,
    public subtitle: string
  ) {
    super(component);
  }
}

class HeaderSlide extends Slide {
  constructor(component: ComponentType, public header: string) {
    super(component);
  }
}

// 无需手动指定类型,TypeScript会自动推导所有子类实例的联合类型
const slides = [
  new TitleSlide(TitleSlideComponent, 'Title', 'Subtitle'),
  new HeaderSlide(HeaderSlideComponent, 'Header'),
];

关键说明

  • 纯接口方案无法自动收集子类型,因为TypeScript的接口是鸭子类型,没有“所有继承ISlide的接口”这种内置集合类型。
  • 两种方案都能实现需求:注册表方案保留接口的灵活性,类方案更符合面向对象的继承逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:53:23