在打字稿中,我想创建一个接受2个对象的函数,然后将Object.assign分配给新对象,并进行类型检查以确保两个对象都没有相同的键。
I tried使用k in keyof T
的各种形式,但没有成功。
function combine<T extends Object, U extends { [K in keyof T]: undefined }>(obj1: T, obj2: U) {
return {
...obj1,
...obj2
}
}
结果未进行正确的类型检查
// setup objects
const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}
// I need this to only error when properties on test 2 exist in test 1
// should pass
const result = combine(test1, test2)
/* Resulting error:
Argument of type '{ something: string; }' is not assignable to parameter of type '{ test: undefined; }'.
Property 'test' is missing in type '{ something: string; }' but required in type '{ test: undefined; }'.
*/
// should fail and does fail
const result2 = combine(test1, test3)
/* Resulting error:
Argument of type '{ test: {}; }' is not assignable to parameter of type '{ test: undefined; }'.
Types of property 'test' are incompatible.
Type '{}' is not assignable to type 'undefined'.
*/
答案 0 :(得分:2)
类似的方法也可以:
function combine<T extends object, U extends object>(
obj1: keyof T extends keyof U ? never : T,
obj2: keyof U extends keyof T ? never : U,
) {
return {
...obj1,
...obj2,
}
}
游乐场here
答案 1 :(得分:1)
强迫自己组织足够多的事情来组织一个问题gave me an idea,该问题最终得以解决。我很想看看是否有人有更好的方法。
const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}
function combine<T extends Object, U extends Object & { [K in keyof T]?: undefined }>(obj1: T, obj2: U) {
return {
...obj1,
...obj2
}
}
// I need this to only error when properties on test 2 exist in test 1
const result = combine(test1, test2) // should pass
const result2 = combine(test1, test3) // should fail
U extends Object & { [K in keyof T]?: undefined}
-扩展对象最终摆脱了has no properties in common with type
错误。