无法推断属性类型,即使它是从记录定义扩展的



我很困惑为什么当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。不需要额外的泛型参数!

游乐场

最新更新