首页 > 其他分享 >[Typescript] Infer from an Interface

[Typescript] Infer from an Interface

时间:2022-12-12 15:23:47浏览次数:54  
标签:Typescript type getName getPoint getContext MyComplexInterface Interface interfa

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 }>>];

 

标签:Typescript,type,getName,getPoint,getContext,MyComplexInterface,Interface,interfa
From: https://www.cnblogs.com/Answer1215/p/16976109.html

相关文章