我很困惑为什么当TParent
扩展Record<TParentProperty, TChild>
时,typescript无法推断destination[destinationProperty]
是TChild
,这应该允许它推断属性是TChild
类型。
class Person {
favoriteDog: Dog | undefined;
}
class Dog {
name: string;
}
function mapSingle<
TChild extends object | undefined,
TParent extends Record<TParentProperty, TParentPropertyType>,
TParentProperty extends Extract<keyof TParent, string>,
TParentPropertyType extends TChild,
>(
destination: TParent,
destinationProperty: TParentProperty,
source: TChild,
) {
destination[destinationProperty] = source; // Error Line
}
类型'TChild'不能赋值给类型'TParent[TParentProperty]'.
类型"object | undefined"不能赋值给类型"TParent[TParentProperty]"。
类型'undefined'不能赋值给类型'TParent[TParentProperty] .(2322)
Typescript Playground示例
这里有点太复杂了,像这样的东西可以工作:
class Person {
favoriteDog: Dog | undefined;
}
class Dog {
name: string;
}
function mapSingle<
Parent,
ParentProp extends keyof Parent,
Child extends Parent[ParentProp],
>(
destination: Parent,
destinationProperty: ParentProp,
source: Child,
) {
destination[destinationProperty] = source;
}
mapSingle(new Person(), "favoriteDog", new Dog())
mapSingle(new Person(), "favoriteDog", undefined)
这是最简单的版本;您有一个Parent
,属性ParentProp
和该属性的类型Child
。不需要额外的泛型参数!
游乐场