[Typescript] Infer from an Interface

In this exercise we have an interface MyComplexInterface which is acting as a type helper.

The interface takes arguments for EventContextName, and Point, each being put into getEventgetContextgetName, and getPoint, respectively.

interface MyComplexInterface<Event, Context, Name, Point> {
  getEvent: () => Event;
  getContext: () => Context;
  getName: () => Name;
  getPoint: () => Point;
}

 

We want a GetPointtype, just return what getPointholds

type GetPoint<T> = T extends MyComplexInterface<any, any, any, infer TPoint>
  ? TPoint
  : never;

 

import { Equal, Expect } from "../helpers/type-utils";

interface MyComplexInterface<Event, Context, Name, Point> {
  getEvent: () => Event;
  getContext: () => Context;
  getName: () => Name;
  getPoint: () => Point;
}

type Example = MyComplexInterface<
  "click",
  "window",
  "my-event",
  { x: 12; y: 14 }
>;

type GetPoint<T> = T extends MyComplexInterface<any, any, any, infer TPoint>
  ? TPoint
  : never;

type tests = [Expect<Equal<GetPoint<Example>, { x: 12; y: 14 }>>];

 

posted @ 2022-12-12 15:08  Zhentiw  阅读(22)  评论(0)    收藏  举报