使用泛型类型限制建模递归类型

时间:2017-07-18 15:33:59

标签: typescript

是否可以建模一个简单的递归关系,如下所示?我想将添加到通用容器的值的类型限制为基元或其他容器。由于接口不能从类型扩展,并且类型不能引用自身,因此不能立即明确这是否可能:

  type Primitive = string | boolean | number | null;
  type Value = Primitive | MyMap<Value>;  // <-- error here


  interface MyMap<T extends Value> {
    get(k: string): T;
    set(k: string, v: T): void;
  }

1 个答案:

答案 0 :(得分:1)

类型可以引用自己(参见spec),但肯定有陷阱。对于您的具体情况,我可能会做类似的事情:

type Primitive = string | boolean | number | null;

type Value = Primitive | MyMap; 

interface MyMap {
  get(k: string): Value;
  set(k: string, v: Value): void;
}

没有通用的东西。

更新1

@Chris Colbert said

  

通用名称很重要,因为我希望能够做到这样的事情:let m1: MyMap<string>; let m2: MyMap<MyMap<number>>;等等。

好的,试试:

type Primitive = string | boolean | number | null;

type Value = Primitive | {
  get(k: string): Value;
  set(k: string, v: Value): void;
}

interface MyMap<T extends Value> {
  get(k: string): T;
  set(k: string, v: T): void;
}

declare let m1: MyMap<string>; 
declare let m2: MyMap<MyMap<number>>;