Home > Back-end >  How to get keys of type union in TypeScript
How to get keys of type union in TypeScript

Time:10-28

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")[]

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?

CodePudding user response:

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]>[]; 
  • Related