代码之家  ›  专栏  ›  技术社区  ›  xpepermint

对象上的泛型类型

  •  1
  • xpepermint  · 技术社区  · 6 年前

    我有一个简单的类,允许设置和获取类对象的泛型值(假设这个类是由npm包提供的)。

    class Spec {
        protected data = {};
        set<T>(k: string, v: T) {
            this.data[k] = v;
        }
        get(k: string) {
            return this.data[k];
        }
    }
    

    假设我创建这个类的一个实例并设置 id 类型字段 number :

    const spec = new Spec();
    spec.set('id', 100);
    

    当我检索该值时,typescript将该值作为type返回 any 而不是 :

    const id = spec.get('id');
    // id should be of typescript type number (any instead)
    

    我可以手动指定类型,但希望自动处理:

    const id = spec.get<number>('id');
    // or
    const id = spec.get('id') as number;
    

    这种情况有什么办法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    6 年前

    我唯一能想到的是 Spec 有一个泛型参数来表示 data 什么时候 set 被称为, this 返回,但其类型已修改以反映新添加的字段。这种方法的问题是您需要 设置 在将值赋给变量之前,或保持 设置 在新变量中,因为它将具有不同的类型。

    class Spec<TAll = {}>{
      protected data: TAll = {} as any;
      set<TKey extends string, TValue>(k: TKey, v: TValue): Spec<TAll & { [P in TKey]: TValue }> {
        (this.data as any)[k] = v;
        return this as any
      }
      get<TKey extends keyof TAll>(k: TKey) {
        return this.data[k];
      }
    }
    
    
    const spec = new Spec().set('id', 100);
    
    spec.get('id') // is number