[Typescript] Get object prop value

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

type GetPropValue<
  T extends Record<PropertyKey, any>,
  P extends keyof T = "data"
> = T extends {
  [Key in P]: infer TInferredData;
}
  ? TInferredData
  : never;

type tests = [
  Expect<Equal<GetPropValue<{ data: "hello" }>, "hello">>,
  Expect<Equal<GetPropValue<{ data: { name: "hello" } }>, { name: "hello" }>>,
  Expect<
    Equal<
      GetPropValue<{ data: { name: "hello"; age: 20 } }>,
      { name: "hello"; age: 20 }
    >
  >
];

 

posted @ 2022-12-11 22:33  Zhentiw  阅读(25)  评论(0编辑  收藏  举报