Alikhani
Alikhani

Reputation: 33

How can I define Generic type : type as property name typescript

How can I define a generic type GetAppActions if T equals trigger data property only shows trigger and vice versa

type GetAppActionType = 'trigger' | 'action'
interface AppActionInputField {}

type GetAppActions<T = GetAppActionType> = {
    data: {
        action: { inputFields: AppActionInputField[] }
        trigger: { inputFields: AppActionInputField[] }
    }
    type: T
}

Upvotes: 0

Views: 107

Answers (2)

shaktimaan
shaktimaan

Reputation: 1857

You can use discrimating union to help you in restricting data property according to type.

Basically, this acts as a switch for your types.


interface AppActionInputField { }

type GetAppActions = {
  type: "trigger"
  data: {
    trigger: { inputFields: AppActionInputField[] }
  }
} | {
  type: "action",
  data: {
    action: { inputFields: AppActionInputField[] }
  }
}

type GetAppActionType = GetAppActions["type"];
// "actions" | "trigger"

Upvotes: 0

asnaeb
asnaeb

Reputation: 745

You can use a mapped type

interface AppActionInputField {}

type GetAppActions<T extends "trigger"|"action"> = {
    data: {
        [K in T]: { inputFields: AppActionInputField[] }
    },
    type: T
}

const test: GetAppActions<"trigger"> = {
    data: {
        trigger: { inputFields: [{}] }
    },
    type: "trigger"
}

Playground Link

Upvotes: 1

Related Questions