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

如何基于单个IStorage接口让LiveStorage的storage默认仅取CustomStore类型?

解决TypeScript中LiveStorage的类型推导问题

核心思路

通过类型工具从单个IStorage接口中自动提取对应CustomStore类型,无需手动断言或重复定义类型。

实现步骤

1. 定义类型提取工具

编写两个工具类型,从IStorage的联合类型中筛选出CustomStore分支:

// 从联合类型中提取CustomStore<T>类型
type ExtractStore<T> = T extends CustomStore<infer U> ? CustomStore<U> : never;

// 将默认存储类型的所有属性转换为对应的CustomStore类型
type StorageFromDefault<D> = {
  [K in keyof D]: ExtractStore<D[K]>;
};
  • ExtractStore:利用条件类型和infer关键字,自动识别并保留联合类型中的CustomStore部分,丢弃原始值类型(如boolean/number)。
  • StorageFromDefault:映射类型,遍历输入类型的所有键,将每个属性替换为对应的CustomStore类型。

2. 修改LiveStorage类的泛型约束

调整LiveStorage的泛型默认值,让storage的类型自动从默认存储类型推导而来:

class LiveStorage<D = { [key: string]: any }, S = StorageFromDefault<D>> {
  private defaultStorage: D;
  storage: S;

  constructor(defaultStorage: D) {
    this.defaultStorage = defaultStorage;
    this.storage = {} as S;
  }
}

3. 创建实例并验证类型

使用单个IStorage接口创建实例,此时storage的属性会自动推导为CustomStore类型:

interface IStorage {
  key: boolean | CustomStore<boolean>,
  key2: number | CustomStore<number>
}

type CustomStore<T> = {
  value: T,
  init: (value: T) => void;
  set: (value: T) => void;
}

// 仅需传入IStorage作为泛型参数,storage类型自动推导
let liveStorage = new LiveStorage<IStorage>({});

// IDE自动提示类型为CustomStore<boolean>,无需断言
liveStorage.storage.key; 
// 类型为CustomStore<number>
liveStorage.storage.key2;

效果验证

  • 无需手动添加类型断言,IDE直接给出CustomStore的方法提示(如init/set)。
  • 仅依赖单个IStorage接口,避免了类型重复定义的冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:52:47