gpt4 book ai didi

typescript - 将被减数和差的交集分配给被减数和被减数的交集

转载 作者:行者123 更新时间:2023-12-04 10:22:52 31 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





A extends B; Type 'Pick<A, Exclude<keyof A, keyof B>> & B' is not assignable to type 'A'.ts(2322)

(1 个回答)


去年关闭。




我从 mathematical terminology for subtraction 借用了术语减数、被减数和差值。 .

我有两种类型,FooBar ,它应该是简单的对象,其键和值可能有也可能没有重叠的键。我想要一个类型 OnlyFoo这是减数Foo 之间的差值和被减数 Bar .这很简单:

type OnlyFoo = Omit<Foo, keyof Bar>

后来我想分配交集 OnlyFoo & BarFoo & Bar ,但如果没有 TypeScript 给出错误,我就找不到办法做到这一点。

这是一个更具体的代码示例。它基本上是一个函数工厂,它接受一个类型为 OnlyFoo 的对象。并返回一个完整的 Foo & Bar目的。
const test = <Foo, Bar>(bar: Bar) => (
fooOnly: Omit<Foo, keyof Bar>
) => {
const fooBar: Foo & Bar = { ...fooOnly, ...bar };
};

TypeScript 为 fooBar 提供以下错误该代码的分配:
// Type 'Pick<Foo, Exclude<keyof Foo, keyof Bar>> & Bar' is not assignable to type 'Foo & Bar'.
// Type 'Pick<Foo, Exclude<keyof Foo, keyof Bar>> & Bar' is not assignable to type 'Foo'.
// 'Pick<Foo, Exclude<keyof Foo, keyof Bar>> & Bar' is assignable to the constraint of type 'Foo', but 'Foo' could be instantiated with a different subtype of constraint '{}'.ts(2322)

以下是 TypeScript Playground 中的相同示例.

错误消息表明“ Foo 可以使用约束 {} 的子类型实例化”,这将使赋值非法。我似乎想不出任何这样的类型。我可以对 Foo 做进一步的限制吗?使这成为可能?

最佳答案

不幸的是,已知的 TS 限制是 Omit,Exclude 不适用于泛型。看看this issue和回应:

We don't have any mechanisms available that could resolve this. The problem is that Exclude is a higher-order operation; when its input is generic, we don't have any way to predict what comes out the other side.



你唯一能做的就是类型断言:
{ ...fooOnly as Foo, ...bar }

关于typescript - 将被减数和差的交集分配给被减数和被减数的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60758084/

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