当值的类型在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']})
1条答案
按热度按时间knsnq2tg1#
检查有效负载是否扩展了任何内容似乎可以解决这个问题