gpt4 book ai didi

javascript - Typescript Omit 似乎将并集转换为交集

转载 作者:行者123 更新时间:2023-12-02 18:08:41 25 4
gpt4 key购买 nike

我有这种类型

type Cartesian = { kind: 'cartesian'; x: number; y: number; }
type Polar = { kind: 'polar'; angle: number; distance: number }
type Movement = { name: string } & (Cartesian | Polar);

我可以这样使用

const move = (movement: Movement) => { /* whatever */ };
move({ name: 'top right', kind: 'cartesian', x: 10, y: 10 });
move({ name: 'left', kind: 'polar', angle: Math.PI, distance: 10 });

但是由于某些原因,我不能这样使用它

const unnamedMove = (unnamedMovement: Omit<Movement, 'name'>) => {
move({ name: 'default', ...unnamedMovement })
}

因为 TS 抛出一个 2345:

Argument of type '{ kind: "cartesian" | "polar"; name: string; }' is not assignable to parameter of type 'Movement'.
Type '{ kind: "cartesian" | "polar"; name: string; }' is not assignable to type '{ name: string; } & Polar'.
Type '{ kind: "cartesian" | "polar"; name: string; }' is missing the following properties from type 'Polar': angle, distance

我不明白这个。

如果我没记错的话Omit<Movement, 'name'>应该等同于联合类型 Cartesian | Polar , 这将使 { name: 'default', ...unnamedMovement }一个Movement ,一切都应该有效。

但是,看起来 TS 推断出 Omit<Movement, 'name'>好像它是联合类型 Cartesian & Polar ,因此错误。

这是错误还是我的错误?

playground link

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com