为什么我不能返回一个通用的“T"来满足 Partial<T>? [英] Why can't I return a generic 'T' to satisfy a Partial<T>?
问题描述
我用 TypeScript 写了一些代码:
I wrote some code in TypeScript:
type Point = {
x: number;
y: number;
};
function getThing<T extends Point>(p: T): Partial<T> {
// More interesting code elided
return { x: 10 };
}
这会产生一个错误:
输入 '{ x: 10;}' 不可分配给类型 'Partial
这似乎是一个错误 - { x: 10 }
显然是一个 Partial
.TypeScript 在这里做错了什么?我该如何解决这个问题?
This seems like a bug - { x: 10 }
is clearly a Partial<Point>
. What's TypeScript doing wrong here? How do I fix this?
推荐答案
在考虑编写泛型函数时,有一个重要的规则要记住
When thinking about writing a generic function, there's an important rule to remember
您为 getThing
提供的合约 ...
The contract you've provided for getThing
...
function getThing<T extends Point>(p: T): Partial<T>
... 暗示像这样的合法调用,其中 T
是 Point
的子类型:
... implies legal invocations like this one, where T
is a subtype of Point
:
const p: Partial<Point3D> = getThing<Point3D>({x: 1, y: 2, z: 3});
当然,{ x: 10 }
是一个合法的Partial
.
但是子类型化的能力不仅仅适用于添加额外的属性——子类型化可以包括选择一组更受限制的属性本身的域.你可能有这样的类型:
But the ability to subtype doesn't just apply to adding additional properties -- subtyping can include choosing a more restricted set of the domain of the properties themselves. You might have a type like this:
type UnitPoint = { x: 0 | 1, y: 0 | 1 };
现在当你写
const p: UnitPoint = getThing<UnitPoint>({ x: 0, y: 1});
p.x
的值为 10
,它不是一个合法的 UnitPoint
.
p.x
has the value 10
, which is not a legal UnitPoint
.
如果您发现自己处于这样的情况,很有可能您的返回类型实际上不是通用的.更准确的函数签名是
If you find yourself in a situation like this, odds are good that your return type is not actually generic. A more accurate function signature would be
function getThing<T extends Point>(p: T): Partial<Point> {
这篇关于为什么我不能返回一个通用的“T"来满足 Partial<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!