简体   繁体   English

如何定义通用类型:类型为属性名称 typescript

[英]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如果T等于trigger数据属性仅显示trigger ,我如何定义通用类型GetAppActions ,反之亦然

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

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

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 游乐场链接

You can use discrimating union to help you in restricting data property according to type .您可以使用区分联合来帮助您根据type限制data属性。

Basically, this acts as a switch for your types.基本上,这充当您的类型的switch


interface AppActionInputField { }

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 keyof 属性定义通用打字稿类型? - How to define generic typescript type with keyof property? Typescript - 如何根据另一个属性有条件地定义类型 - Typescript - How can I conditionally define a type based on another property 如何在打字稿中按名称检查泛型类型是否具有属性? - How to check whether a generic type has a property by name in typescript? Typescript - 使用字符串获取名称的属性,作为泛型类型 - Typescript - Get property of name with string, as generic type 如何在 TypeScript 中定义通用匿名 function 类型? - How to define a generic anonymous function type in TypeScript? 如何在 Typescript 中定义通用类型保护? - How to define a generic Type Guard in Typescript? 如何为具有通用键的字典定义 typescript 类型? - How to define a typescript type for a dictionary with generic keys? 如何在此泛型类型内的属性的泛型接口内定义类型 - How to define a type inside a generic interface for a property inside this generic type 如何基于泛型类型定义抽象属性 - How to define abstract property based on generic type 我可以在一个类中定义一个特定的类类型,该类在打字稿中实现了一个具有泛型类型的接口吗? - Can I define a specific class type in a class that implements an interface with a generic type in typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM