Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get keys of type union in TypeScript

I’m working on a structure like the one below because I want to access Types dynamically.

type userType = {
    userId: number
    name: string
}

type postType = {
    postId: number,
    title: string
}

type entityTypes = {
    user: userType,
    post: postType
}

I want separated union of entity types keys. So like this:

("userId" | "name)[] | ("postID" | "title")[]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But not this:

("userId" | "name" | "postID" | "title")[]

I’m trying as follows, but it returns never.

type entityFieldsArray = keyof prismaIncludes_t[keyof prismaIncludes_t] //never

Then I found the following solution

type KeysOfUnion<T> = T extends T ? keyof T: never;
type AvailableKeys = KeysOfUnion<entityTypes[keyof entityTypes]>[]; 

But this return:
("userId" | "name" | "postID" | "title")[].
So it’s not separate.

How can I get keys that seperated with parent?
I hope I explained clearly?

>Solution :

So close; you needed to wrap keyof T in the array instead of the entire result:

type KeysOfUnion<T> = T extends T ? (keyof T)[]: never;
type AvailableKeys = KeysOfUnion<entityTypes[keyof entityTypes]>[]; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading