获取其他类型的键的类型(嵌套)

时间:2019-09-30 07:39:22

标签: typescript typescript-typings

我正在使用graphql-codegen,它会生成类似的类型:

type Price = {
  onetime: number;
  monthtly: number;
};

type CarModel = {
  price: Price;
  name: string;
};

type Car = {
  model: CarModel;
  someOtherAttribute: string;
};

type MyCarQuery = Pick<Car, "someOtherAttribute"> & {
  model: Pick<CarModel, "name"> & {
    price: Pick<Price, "onetime">;
  };
};

我想将MyCarQuery -> model -> price的类型提取到它自己的类型中以单独使用。因此,基本上我想拥有Pick<Price, "onetime">的类型定义-不必再次定义它。

有没有复制类型的方法吗?

1 个答案:

答案 0 :(得分:3)

我相信您正在寻找:

type TheType = MyCarQuery["model"]["price"];

On the playground

使用给定的定义将TheType定义为{onetime: number},但是如果更改Price使得onetimestring,则TheType更改为{onetime: string}

我希望我能指出《手册》中描述这一部分的内容,但可悲的是,我不能。据我所知,这是TypeScript不会涵盖的部分之一。 (有几个。:-()我通过阅读SO上的答案来挑选它。