[英]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"
}
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.