简体   繁体   中英

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 . Why does TypeScript think otherwise? Can I get around this without a type assertion?

You can use Object.assign to avoid a type assertion:

const tagProduct = (product: Product): TaggedProduct => {
  const tag: string = "anything";
  return Object.assign(product, {tag});
}

This is because Object.assign is typed like this:

interface ObjectConstructor {
  assign<T, U>(target: T, source: U): T & U;
}

and so the return type of Product & {tag: string} is assignable to TaggedProduct .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM