英文:
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"]>;
英文:
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"]>;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论