TypeScript:从嵌套类型获取类型

huangapple go评论54阅读模式
英文:

TypeScript: Get type from a nested type

问题

I have a type (Note: Both a and foo can be optional):

type Something = {
  a?: {
    foo?: {
      bar: {
        c: {
          id: string,
          countryCode: number,
          animal: { ... }
        }
      }
    }
  }
}

Now I want to have another type MyType, which is bar in the example above. So MyType will be:

type MyType = {
  c: {
    id: string,
    countryCode: number,
    animal: { ... }
  }
}

My question: How could I create MyType from type Something?

Update: See this comment for the answer: Stack Overflow Comment

英文:

I have a type (Note: Both a and foo can be optional):

type Something = {
  a?: {
    foo?: {
      bar: {
        c: {
          id: string,
          countryCode: number,
          animal: { ... }
        }
      }
    }
  }
}

Now I want to have another type MyType, which is bar in the example above. So MyType will be:

type MyType = {
  c: {
    id: string,
    countryCode: number,
    animal: { ... }
  }
}

My question: How could I create MyType from type Something?

Update: See this comment for the answer: https://stackoverflow.com/questions/76333795/typescript-get-type-from-a-nested-type?noredirect=1#comment134607414_76333795

答案1

得分: 1

The easiest way would be:
type MyType = NonNullable<NonNullable<Something["a"]>["foo"]>["bar"];

However, I can suggest a more dynamic approach as well:

type Something = {
  a?: {
    foo?: {
      bar: {
        c: {
          id: string;
          countryCode: number;
        };
      };
    };
  };
};

type RetrieveSubProperty<T, K extends string[]> = [] extends K
  ? T
  : K extends [infer First extends keyof T, ...infer Rest extends string[]]
  ? RetrieveSubProperty<NonNullable<T[First]>, Rest>
  : never;

type Bar = RetrieveSubProperty<Something, ["a", "foo", "bar"]>;

playground

英文:

The easiest way would be:
type MyType = NonNullable&lt;NonNullable&lt;Something[&quot;a&quot;]&gt;[&quot;foo&quot;]&gt;[&quot;bar&quot;];

However, I can suggest a more dynamic approach as well:

type Something = {
  a?: {
    foo?: {
      bar: {
        c: {
          id: string;
          countryCode: number;
        };
      };
    };
  };
};

type RetrieveSubProperty&lt;T, K extends string[]&gt; = [] extends K
  ? T
  : K extends [infer First extends keyof T, ...infer Rest extends string[]]
  ? RetrieveSubProperty&lt;NonNullable&lt;T[First]&gt;, Rest&gt;
  : never;

type Bar = RetrieveSubProperty&lt;Something, [&quot;a&quot;, &quot;foo&quot;, &quot;bar&quot;]&gt;;

playground

huangapple
  • 本文由 发表于 2023年5月25日 23:07:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定