在这种情况下,key 不是keyof Partial<T> - 它的类型扩展了keyof P,其中P 扩展了 Partial<T>。 P 可能有比T 更多/不同的键,所以key 不能在这里用作T 的属性。
假设你不想给T添加新的属性,就不需要有类型参数P,因为它可以从T本身推断出来。这里有两种解决方案,取决于您是否希望 obj 从 part 获取 undefined 属性值:
// no undefined values assigned from part
function updateWithPartial<T, K extends keyof T>(obj: T, part: Partial<T>, key: K) {
if (part[key] === undefined) throw new Error() // throw or do something else...
return obj[key] = part[key] as T[K] // help compiler to understand, part[key] must be defined here
}
// possible undefined values assigned from part
function updatePartialWithPartial<T, K extends keyof T>(obj: Partial<T>, part: Partial<T>, key: K) {
return obj[key] = part[key]
}
好的,一些测试:
declare const foo: { a: string }
const res = updateWithPartial(foo, { a: "bar" }, "a") // string
const res2 = updatePartialWithPartial(foo, { a: "bar" }, "a") // string | undefined
const res22 = updatePartialWithPartial(foo, {}, "a") // string | undefined
Playground