TypeScript:从嵌套类型获取类型

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

TypeScript: Get type from a nested type

问题

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

  1. type Something = {
  2. a?: {
  3. foo?: {
  4. bar: {
  5. c: {
  6. id: string,
  7. countryCode: number,
  8. animal: { ... }
  9. }
  10. }
  11. }
  12. }
  13. }

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

  1. type MyType = {
  2. c: {
  3. id: string,
  4. countryCode: number,
  5. animal: { ... }
  6. }
  7. }

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):

  1. type Something = {
  2. a?: {
  3. foo?: {
  4. bar: {
  5. c: {
  6. id: string,
  7. countryCode: number,
  8. animal: { ... }
  9. }
  10. }
  11. }
  12. }
  13. }

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

  1. type MyType = {
  2. c: {
  3. id: string,
  4. countryCode: number,
  5. animal: { ... }
  6. }
  7. }

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:

  1. type Something = {
  2. a?: {
  3. foo?: {
  4. bar: {
  5. c: {
  6. id: string;
  7. countryCode: number;
  8. };
  9. };
  10. };
  11. };
  12. };
  13. type RetrieveSubProperty<T, K extends string[]> = [] extends K
  14. ? T
  15. : K extends [infer First extends keyof T, ...infer Rest extends string[]]
  16. ? RetrieveSubProperty<NonNullable<T[First]>, Rest>
  17. : never;
  18. 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:

  1. type Something = {
  2. a?: {
  3. foo?: {
  4. bar: {
  5. c: {
  6. id: string;
  7. countryCode: number;
  8. };
  9. };
  10. };
  11. };
  12. };
  13. type RetrieveSubProperty&lt;T, K extends string[]&gt; = [] extends K
  14. ? T
  15. : K extends [infer First extends keyof T, ...infer Rest extends string[]]
  16. ? RetrieveSubProperty&lt;NonNullable&lt;T[First]&gt;, Rest&gt;
  17. : never;
  18. 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:

确定