结构歧视联盟

时间:2018-05-09 23:50:11

标签: typescript

我正在尝试编写适用于具有type属性的通用区分联合的代码。

让我们说我有很多受歧视的工会,如:

interface IFoo {
  type: "foo";
  foo: number;
}

interface IBar {
  type: "bar";
  bar: number;
}

interface IBaz {
  type: "baz";
  baz: number;
}

type IObject = IFoo | IBar | IBaz;

我解决的第一个任务是确定type属性的可能值:

declare let _object: IObject;
type ObjectType = typeof _object.type;

(顺便说一句没有额外声明的方法吗?)

我需要声明一个泛型类型,如:

Case<IObject, "foo"> // = IFoo
Case<IObject, "bar"> // = IBar

这样我就可以声明:

function filter<Type extends ObjectType>(
    objects: IObject[], 
    type: Type,
): Case<IObject, type>[] {
  return objects.filter((o) => o.type == type);
}

这可能吗?

1 个答案:

答案 0 :(得分:1)

是的,可能

interface IFoo {
  type: "foo";
  foo: number;
}

interface IBar {
  type: "bar";
  bar: number;
}

interface IBaz {
  type: "baz";
  baz: number;
}

type IObject = IFoo | IBar | IBaz;

type TypeSwitch<N extends string, T extends { type: N }> =
       { [n in N]: T extends { type: n } ? T : never };

type Case<T extends { type: string }, N extends T['type']> =
       TypeSwitch<T['type'], T>[N];

type F = Case<IObject, "foo">; // = IFoo
type B = Case<IObject, "bar">; // = IBar

此外,您可以使用&#39;索引类型查询&#39;来引用属性的类型。 type运算符(实际上与[]的属性访问语法相同,只对类型进行操作)

type ObjectType = IObject['type'];

最后,在filter中使用以上所有内容可以按预期方式给出过滤后的数组元素的类型:

function filter<Type extends ObjectType>(
    objects: IObject[], 
    type: Type,
): Case<IObject, Type>[] {
  return objects.filter((o) => o.type == type);
}


let o: IObject[];
const a = filter(o, 'bar'); // inferred as const a: IBar[]