无法推断 属性 类型,即使它是从记录定义扩展的
Unable to infer property type even though it's extending from a record definition
我很困惑为什么 typescript 在 TParent
扩展 Record<TParentProperty, TChild>
时无法推断 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
}
Type 'TChild' is not assignable to type 'TParent[TParentProperty]'.
Type 'object | undefined' is not assignable to type 'TParent[TParentProperty]'.
Type 'undefined' is not assignable to type 'TParent[TParentProperty]'.(2322)
这里有点复杂,像这样的东西可以工作:
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
的类型。不需要额外的通用参数!
我很困惑为什么 typescript 在 TParent
扩展 Record<TParentProperty, TChild>
时无法推断 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
}
Type 'TChild' is not assignable to type 'TParent[TParentProperty]'.
Type 'object | undefined' is not assignable to type 'TParent[TParentProperty]'.
Type 'undefined' is not assignable to type 'TParent[TParentProperty]'.(2322)
这里有点复杂,像这样的东西可以工作:
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
的类型。不需要额外的通用参数!