Typescript:使一个参数的类型依赖于另一个参数的值



我试图创建一个函数,其中一个参数依赖于另一个。我不能让它工作,它开始让我发疯。下面是我要做的:

export interface LaneLayout {
i: number;
x: number;
y: number;
w: number;
h: number;
lane_content: string;
project_id: number;
}
export type Action = "modify" | "create";
export type ModifiedLaneLayout = Omit<
LaneLayout,
"project_id" | "lane_content"
>;
export type CreatedLaneLayout = Pick<LaneLayout, "x" | "y">;
export type LayoutType<T extends Action> = T extends "modify"
? ModifiedLaneLayout
: T extends "create"
? CreatedLaneLayout
: never;
export function modifyBox<K extends Action>(
action: K,
layout: LayoutType<K>
): void {
if (action === "modify") {
layout.h; // property h should exist here
} else {
layout.h // property h should not exist here
}
}

在函数中,似乎无论action的值如何,布局参数的类型总是CreatedLaneLayout,并且属性h在if语句的两种情况下都不存在。我遗漏了什么?

您需要将两个参数连接到一个对象中(并且在此之后modifyBox将不再是泛型函数):

type ModifyBoxArgument
= {action: 'create'; layout: CreatedLaneLayout}
| {action: 'modify'; layout: ModifiedLaneLayout}
export function modifyBox(arg: ModifyBoxArgument): void {
if (arg.action === "modify") {
arg.layout.h; // property h should exist here
} else {
arg.layout.h // property h should not exist here
}
}

但是请记住,你不能解构arg,直到你进入if的主体(或在else部分),否则它会阻止编译器跟踪actionlayout类型之间的依赖关系。

游乐场

相关内容

最新更新