Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Suppose I have the following code:

interface A {     a: number; }  interface B extends A {     b: number; }  const b: B = {a: 1, b: 5}; const a: A = b as A; 

Now the variable a has type A, but it still contains b inside of it. Sometimes it is undesirable - I'd like to be sure that, if I have a variable of type A, it has the exact fields of type A. I was wondering, whether TypeScript has some kind of a "hard cast" which would remove any unneeded fields when converting between types.

like image 450
SalysBruoga Avatar asked May 16 '18 19:05

SalysBruoga


People also ask

How do you typecast an object in TypeScript?

In TypeScript, you can use the as keyword or <> operator for type castings.

Can you cast in TypeScript?

Surprisingly, the typescript programming language, which compiles to JavaScript, has the idea of casting. Since the variables in JavaScript have dynamic types, there is no concept of type casting in Javascript. TypeScript, on the other hand, assigns a type to every variable.

What is omit in TypeScript?

The TypeScript Omit utility type Like the Pick type, the Omit can be used to modify an existing interface or type. However, this one works the other way around. It will remove the fields you defined. We want to remove the id field from our user object when we want to create a user.


1 Answers

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.

like image 84
Sefe Avatar answered Sep 16 '22 12:09

Sefe