Home > Back-end >  How can I define Generic type : type as property name typescript
How can I define Generic type : type as property name typescript

Time:09-02

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
}

CodePudding user response:

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

CodePudding user response:

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"
  • Related