Typescript cast to class

Typescript cast to class

“Typecast types in Typescript” : that’s three “types” in a sentence with three significant words, and for that, I should tap out (but I don’t).

We see a lot about “type assertions” in to type conversations (or conversions!) in Typescript. Type assertions enable you to override default type inference for neutral types. We have discussed about type assertion before.

Typecasting refers to type conversions. While they don’t function similar to other strongly typed languages, they do exist.

We will see more of type assertions and casting after this preface.

Types, you say?

For a basic introduction of “types” — head over to types in Typescript and Javascript types.

  • built-in types (basic e.g. number , string , boolean ,and special types e.g. any , unknown )
  • additional types (e.g. collections like enum and even user-defined types)

You define variables with types —

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
let decimal: number = 1; let color: string = "indigo"; // anything, really let notSure: any = "abc"; // collections let list: number[] = [1, 2, 3]; enum Color  Red, Green, Blue, > let c: Color = Color.Green; 

It’s all a good world with types until it isn’t. It so happens that —

  • you (think you) know more than what the compiler knows. You want to tell compiler that a variable is of a specific type.
  • values may need to be moved across types in the course of doing something

Type Assertions and Typecasting

The process of changing types is what is called “type casting”. Typecasting in strongly typed languages like C# allow us to convert types.

string numStr = "123"; int numNum; bool isParsable = Int32.TryParse(numStr, out numNum); 

The code checks whether a given string is a valid number and outputs the number. The “string” or “number” types are treated in a consistent way by both the compiler and runtime engine.

Typescript behaves differently. It is compiled to Javascript, which does not give two hoots about your defined types, and there is no “runtime” to enforce types during execution. All Typescript can do is to apply all its smarts during compilation of Typescript to Javascript code.

Type assertions let the Typescript compiler know that a given variable should be treated as belonging to a certain type. There are no “exceptions” or data restructuring associated with assertions, except minimal validations (we refer this behaviour as “validations that are applied statically”).

But, implicit types do exist during program execution, and type conversion behaves similar to Javascript since the execution engine is, well, Javascript. But, you need to make explicit conversions in Typescript to humour the compiler, and probably, everyone else in your team.

Aside: IMO it is more fun to use implicit conversions that reduce code, confuse people and make it hard to write tests.

When & where to use type casting and type assertion?

Type assertions helps you to force types when you are not in control of them. For e.g. —

  1. you are processing user data (with unreliable types)
  2. working with data that has changed shape over years (employee code was numeric, now it is alphanumeric :))
  3. receiving data from an external program

Consider this example that uses any , a special type that represents any type in Typescript. You convert any to a specific type to process it further —

let whatanum: any = 42; whatanum = "is this the answer to everything?"; whatanum = true; 

We can start with any and use type assertion to denote that the variable is in fact a number.

let whatNum: any = 42; let reallyNum = number>whatNum; console.log(typeof reallyNum); // number 

Or, consider this example with unknown , another special type in Typescript —

const clueless: unknown = "1"; const clueNum: number = number>clueless; // another format const clueNumPreferred = clueless as number; 

The compiler does not know better about any or unknown variables to process further — so we make the compiler “see” the variables for what they really are.

Typecasting, on the other hand, helps you to convert types and provide consistent (expected) results :). For e.g. —

  1. concatenation of a number and string
  2. convert arrays of numbers to strings for formatting and display

How do I assert types?

There are two ways to do type assertions.

  1. Bracket syntax. e.g. let length: number = (lengthField);
  2. Use as . e.g. let length: number = (lengthField as string);

There is no difference between the two ways and the end result is always the same. Note that if you are using JSX you have to use as syntax.

Type conversion in Typescript

Converting specific types is similar to Javascript.

From _ to String

We convert any type to string by using String(x) or x.toString .

console.log(String(42)); //"42" console.log(typeof String(42)); // "string" console.log(String(true)); //"true" console.log(String(undefined)); //"undefined" 

From _ to Number

This is so radically different from string.

Number("0"); // 0 Number("abc"); //NaN Number(true); // 1 

There are additional helper functions that, well, help you do strange things —

parseInt("42life"); //42 parseFloat("3.14pi"); //3.14 

From _ to Boolean

Boolean("a"); // true Boolean(null); // false 

From object to array

Yes, you read that right — let’s see an example of converting object to array in style. Not quite a glaring example of “type conversions”, but apparently, people stare in awe at such code.

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 
const planets: Object =  mercury:  name: "Mercury", position: 1 >, venus:  name: "Venus", position: 2 >, earth:  name: "Earth", position: 3 >, >; const planetsArr: ArrayObject> = Object.keys(planets).map( (key: string): string => planets[key] ); console.log("planetsArr", planetsArr); /* output: [ < name: "Mercury", position: 1 >, < name: "Venus", position: 2 >, < name: "Earth", position: 3 >, ] */ 

The End

We saw type assertions, typecasting and examples of type conversions. Hopefully that has confused you a bit more about the wonderful world of types.

Источник

Cast a JSON Object to a Class in TypeScript

Cast a JSON Object to a Class in TypeScript

  1. Use Object.assign to Cast From JSON to Class in TypeScript
  2. Use Custom Methods to Cast a JSON String to Class in TypeScript

The data on the internet flows in the form of strings and can be converted to a very popular format called JSON. This JSON representation of the data often represents an object or even a class in TypeScript.

TypeScript provides the functionality to cast an object to a class. This article will discuss how to transform the received object into a TypeScript class to make type support, IDE completions, and other features accessible.

Use Object.assign to Cast From JSON to Class in TypeScript

The Object.assign method gives an easy way of converting JSON objects to a TypeScript class so that the methods associated with the class also become accessible.

The following code segment shows how a JSON object can be cast to a TypeScript class using the Object.assign method.

class Animal  name : string;  legs : number;  eyes : number;  constructor(name? : string, legs? : number, eyes? : number)   this.name = name ?? 'Default name';  this.legs = legs ?? 0;  this.eyes = eyes ?? 0;  >   getName()  return this.name;  >   getEyes()  return this.eyes;  > >  var jsonString : string = `  "name" : "Tiger",  "legs" : 4,  "eyes" : 2 >`  var animalObj = new Animal(); console.log(animalObj.getEyes()); Object.assign(animalObj, JSON.parse(jsonString)); console.log(animalObj.getEyes()); 

In the above example, the getEyes() method returned 0 , which was the default value, and when the parsed JSON object was assigned to the animalObj object, it returned 2 , the value in the JSON string.

Use Custom Methods to Cast a JSON String to Class in TypeScript

One can have custom methods such as fromJSON to cast a JSON object to the respective class in TypeScript. This method is more useful as it gives more power to the user.

class Animal  name : string;  legs : number;  eyes: number;  constructor(name : string, legs : number, eyes: number)  this.name = name;  this.legs = legs;  this.eyes = eyes;  >   getName()  return this.name;  >   toObject()  return   name : this.name,  legs : this.legs.toString(),  eyes : this.eyes.toString()  >  >   serialize()   return JSON.stringify(this.toObject());  >   static fromJSON(serialized : string) : Animal   const animal : ReturnTypeAnimal["toObject"]> = JSON.parse(serialized);   return new Animal(  animal.name,  animal.legs,  animal.eyes  )  > >  var jsonString : string = `  "name" : "Tiger",  "legs" : 4,  "eyes" : 2 >`  var animalObj : Animal = Animal.fromJSON(jsonString); console.log(animalObj) // this will work now  console.log(animalObj.getName()); 
Animal:   "name": "Tiger",  "legs": 4,  "eyes": 2 > "Tiger" 

Shuvayan is a professional software developer with an avid interest in all kinds of technology and programming languages. He loves all kinds of problem solving and writing about his experiences.

Источник

Читайте также:  Html div head center
Оцените статью