[英]Why can't I return a generic 'T' to satisfy a Partial<T>?
I wrote some code in TypeScript:我在 TypeScript 中写了一些代码:
type Point = {
x: number;
y: number;
};
function getThing<T extends Point>(p: T): Partial<T> {
// More interesting code elided
return { x: 10 };
}
This produces an error:这会产生一个错误:
Type '{ x: 10; }' is not assignable to type 'Partial<T>'
This seems like a bug - { x: 10 }
is clearly a Partial<Point>
.这似乎是一个错误 -
{ x: 10 }
显然是Partial<Point>
。 What's TypeScript doing wrong here? TypeScript 在这里做错了什么? How do I fix this?
我该如何解决?
When thinking about writing a generic function, there's an important rule to remember在考虑编写泛型函数时,要记住一条重要规则
The contract you've provided for getThing
...您为
getThing
提供的getThing
...
function getThing<T extends Point>(p: T): Partial<T>
... implies legal invocations like this one, where T
is a subtype of Point
: ... 暗示像这样的合法调用,其中
T
是Point
的子类型:
const p: Partial<Point3D> = getThing<Point3D>({x: 1, y: 2, z: 3});
Of course, { x: 10 }
is a legal Partial<Point3D>
.当然,
{ 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 };
Now when you write现在当你写
const p: UnitPoint = getThing<UnitPoint>({ x: 0, y: 1});
px
has the value 10
, which is not a legal UnitPoint
. px
的值为10
,这不是合法的UnitPoint
。
If you find yourself in a situation like this, odds are good that your return type is not actually generic .如果您发现自己处于这样的情况,很有可能您的返回类型实际上不是 generic 。 A more accurate function signature would be
更准确的函数签名是
function getThing<T extends Point>(p: T): Partial<Point> {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.