问题描述
我用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<Point>
. 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
...
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<Point3D>
.
但是子类型化功能不仅仅适用于添加其他属性-子类型化可以包括选择属性本身域的一组更受限的集合.您可能具有这样的类型:
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
.
如果您发现自己处于这种情况,则很可能您的返回类型实际上不是通用的.更准确的功能签名应该是
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> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!