Skip to content

Instantly share code, notes, and snippets.

@tusharsnx
Created June 15, 2022 15:00
Show Gist options
  • Save tusharsnx/bc895619cb0d6a709664860593de8c43 to your computer and use it in GitHub Desktop.
Save tusharsnx/bc895619cb0d6a709664860593de8c43 to your computer and use it in GitHub Desktop.
Apply Partial Recursively on Object Types
type PartialRecur<T> = T extends {} ? { [K in keyof T]?: PartialRecur<T[K]> } : T
@tusharsnx
Copy link
Author

Applies Partial recursively to all the key's value.
example:

type PartialRecur<T> = T extends {} ? { [K in keyof T]?: PartialRecur<T[K]> } : T
type APIResp = PartialRecur<{
    payload: {
        web_url: string
        created_at: {
            year: true
        }
    }
}>

// result: 
type APIResp = {
    payload?: {
        web_url?: string | undefined;
        created_at?: {
            year?: true | undefined;
        } | undefined;
    } | undefined;
}

Use-Case:

  • server response should not be assumed to have certain fields, defining type for response object in this way forces us to use optional chaining while accessing object props.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment