Why is TypeScript refusing to compile this code snippet?
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 find it confusing that adding a tag
field to a Product
doesn't automatically create a TaggedProduct
. Is there a way around this without using a type assertion?