How to cast object to another type and remove unneeded fields in TypeScript?

There is no casting in TypeScript because that’s not how TypeScript works. TS is a type layer on top of JS. When you assign a type in TS you don’t set a type, you annotate that the given expression is of a certain type. When the TS code is transpiled to JS, all type information is stripped.

Or in other words: the type system is JS, with TS you just announce that a variable is of a certain type. More often than never it happens that you assign the wrong type at design time and get suprised during debug that the variable has a completely different type than expected.

If you want to be sure that a property is removed from an object, you need to go the JS way (and – if necessary – annotate the result with TS). Check this Q&A to see how to remove properties from an object.

Leave a Comment