是否可以合并两个通用对象类型的道具?我有一个类似这样的功能:
function foo<A extends object, B extends object>(a: A, b: B) {
return Object.assign({}, a, b);
}
Run Code Online (Sandbox Code Playgroud)
我希望该类型是A中B中不存在的所有属性,以及B中的所有属性.
merge({a: 42}, {b: "foo", a: "bar"});
Run Code Online (Sandbox Code Playgroud)
给出一个相当奇怪的类型{a: number} & {b: string, a: string},a虽然是一个字符串.实际的返回给出了正确的类型,但我无法想象我将如何明确地写它.
我有以下代码。
type Bar<A> = { f: A };
type Result<A> = { r: A };
function foo<A>(
f: (o: A, b: A extends object ? Bar<A> : undefined) => Result<A>
) {
return undefined as any;
}
const func = <A extends object>(b: Bar<A>) => {
return foo<A>((o: A, typeError: Bar<A>) => {
return undefined as any;
})
};
Run Code Online (Sandbox Code Playgroud)
我在名为 的参数的匿名函数中收到 (2) 个类型错误typeError。就它了type undefined/object is not assignable to type Bar<A>。我觉得这很奇怪,因为它A显然延伸了object,所以我们应该处于它不是undefined联盟的情况。
我有以下场景。
function foo<A extends object, B extends A>(
a: A,
b: Pick<B, Exclude<keyof B, keyof A>>
): B {
return undefined as any;
}
const r = foo<{ a: string }, { a: string; b: number }>({ a: "" }, { b: 2 });
Run Code Online (Sandbox Code Playgroud)
我想b成为一个只有不在a. 但我也想在将它们合并在一起时获得结果对象的类型。