[英]TypeScript: why I cannot remove this type assertion?
Why this piece of code won't compile?为什么这段代码不能编译?
interface TaggedProduct {
tag: string;
}
interface Product {
tag?: string;
}
const tagProduct = (product: Product): TaggedProduct => {
const tag: string = "anything";
product.tag = tag;
// Type 'Product' is not assignable to type 'TaggedProduct'.
// Property 'tag' is optional in type 'Product' but required in type 'TaggedProduct'.ts(2322)
return product; // Won't compile
}
I would think that if you add a tag
field to a Product
, you necessarily have a TaggedProduct
.我认为,如果您将
tag
字段添加到Product
,则您必然有一个TaggedProduct
。 Why does TypeScript think otherwise?为什么 TypeScript 不这么认为? Can I get around this without a type assertion?
我可以在没有类型断言的情况下解决这个问题吗?
You can use Object.assign
to avoid a type assertion:您可以使用
Object.assign
来避免类型断言:
const tagProduct = (product: Product): TaggedProduct => {
const tag: string = "anything";
return Object.assign(product, {tag});
}
This is because Object.assign
is typed like this:这是因为
Object.assign
是这样输入的:
interface ObjectConstructor {
assign<T, U>(target: T, source: U): T & U;
}
and so the return type of Product & {tag: string}
is assignable to TaggedProduct
.因此
Product & {tag: string}
的返回类型可分配给TaggedProduct
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.