如果值类型作为泛型对象的属性存在,则需要对象类型的Typescript make属性

llmtgqce  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(134)

当值的类型在Typescript泛型中不作为对象存在时,如何使对象类型的属性成为必需的、可选的甚至隐藏的?

type ActionBaseType {
    payload?: any
    extra?: any
}

type Action<ActionType extends ActionBaseType = ActionBaseType> = {
    extra?: ActionType['extra']
    payload?: ActionType['payload']
} 

// here I should not be able to pass payload or it should be optional, 
// since I did not give a type to payload
const action: Action<{extra: number}> = {extra: 1}   

// here the value should REQUIRE me to pass payload
const action: Action<{extra: number, payload: {id: number}}> = {extra: 1, payload: {id: 2}}

我尝试过但没有成功的方法:

type Action<ActionType extends ActionBaseType = ActionBaseType> = {
     extra?: ActionType['extra']
     payload?: ActionType['payload'] extends never ? undefined : ActionType['payload']
 } 
 // and
 type Action<ActionType extends ActionBaseType = ActionBaseType> = {
     extra?: ActionType['extra']
 } & (ActionType['payload'] extends never ? {} : {payload: ActionType['payload']})
knsnq2tg

knsnq2tg1#

检查有效负载是否扩展了任何内容似乎可以解决这个问题

type ActionBaseType = {
    payload?: any
    extra?: any
}

type Action<ActionType extends ActionBaseType = ActionBaseType> = ActionType extends {
    payload: any
}
    ? {
          extra?: ActionType['extra']
          payload: ActionType['payload']
      }
    : {
          extra?: ActionType['extra']
          payload?: ActionType['payload']
      }

相关问题