- Convert String to Number in Typescript
- Unary plus (+)
- Parseint
- Parsefloat
- Number global function
- Check for NaN
- How to convert any type to object in Angular Code example
- Convert any type to object using Type assertion(generic) symbol
- Convert any type to an object using as a keyword
- How to convert any type to string in typescript?
- How to cast any interface or object into Angular Class (Type)
- Typescript convert any to number one
- Types, you say?
- Type Assertions and Typecasting
- When & where to use type casting and type assertion?
- How do I assert types?
- Type conversion in Typescript
- From _ to String
- From _ to Number
- From _ to Boolean
- From object to array
- The End
Convert String to Number in Typescript
There are several ways you can convert Typescript String to Number. The best way is to make use of the unary plus + operator or the Number global function. You can make use of the parseint or parsefloat functions. The following examples show how to make use of these functions.
Unary plus (+)
The Unary plus (+) operator converts all string representations of numbers, boolean values(true and false), and null to numbers. If the operand cannot be converted into a number, the unary plus operator will return NaN .
The following are some of the examples
- Tries to convert any string to a number
- It converts empty string / Null to 0
- True is 1 and False is 0
- Converts Octal/Hexa numbers to decimal.
- Works correctly on scientific notation numbers.
- In case it fails to convert, then returns NaN
Parseint
The parseint function parses an string and returns an integer. The syntax of the parseInt is as follows. If you do not provide the radix then it assumes the Hexadecimal number.
- Tries to convert any string to a integer and not to floating number
- Converts empty strings, null, infinity, True & false to a NaN
- If the string begins with 0x then it treats it a Hexadecimal number.
- It does not recognize the octal number that begins with 0o
- The older browsers will treat the number starting with 0 as Octal.
- Ignores the Leading & trailing spaces
- If only the initial part of the string is a number, then it converts into number and ignores the rest.
You can make use of the radix . The radix can be from 2 to 36. Use 2 for binary, 8 for octal, 10 for decimal & 16 for HexaDecimal number.
Parsefloat
ParseFloat is another way to convert string to a number.
- Tries to convert any string to a decimal or an integer number
- Converts empty strings, null, True & false to a NaN
- Returns infinity as it is.
- It the string begins with 0x or 0o it returns zero. Does not recognize Hexa decimal or octal numbers
- Ignores the Leading & trailing spaces
- If only the initial part of the string is a number, then it converts into number and ignores the rest.
Number global function
You can also use the Number global function. It is very similar to unary plus ( + )
- Tries to convert any string to a number
- It converts empty string / Null to 0
- True is 1 and False is 0
- Converts Octal/Hexa numbers to decimal.
- Works correctly on scientific notation numbers.
- In case it fails to convert, then returns NaN
Check for NaN
The string to number operation may result in a NaN . The NaN stands for not a number. It is the result of numerical operations, where the result is not a number. Hence always check if the value is NaN using the isNaN method after the conversion.
How to convert any type to object in Angular Code example
Learn to convert or cast any type in typescript to an object with examples in Angular.
This tutorial covers the following things
- How to change variable type in typescript
- Convert any type to string or number in Angular.
- Parse any type of Interface or class in Angular.
In typescript, There is no typecasting, but we have type assertions. So There are two approaches to casting any object to different data types.
Convert any type to object using Type assertion(generic) symbol
Type assertion is a way of telling the compiler about a variable as a type instead of inferring the value.
For example, declare a variable of type any with a numeric value.
when we assigned this to another variable, we are telling the compiler and parse this as a number.
let numb: any = 111; let id = number> numb; console.log(typeof(id)); //Output: number
And another way to use it as a keyword.
Convert any type to an object using as a keyword
let numb: any = 111; let id = numb as number; console.log(typeof(id)); //Output: number
Generics <> will not work in files with TSX files, as the keyword is the preferred way to cast from one type to another type.
How to convert any type to string in typescript?
In the following example, variable of type any is parsed into string variable using generics in typescript.
display(anyvalue: any) this.str = string> anyvalue; >
We can also use it as a keyword which is preferable in typescript.
display(anyvalue: any) this.str = anyvalue as string; >
import Component, VERSION > from ‘@angular/core’; @Component( selector: ‘my-app’, templateUrl: ‘./app.component.html’, styleUrls: [‘./app.component.css’] >) export class AppComponent str = ‘hello’; constructor() this.display(123); > display(anyvalue: any) this.str = string> anyvalue; > >
How to cast any interface or object into Angular Class (Type)
Sometimes, API returns data of any type, So you need to convert it to interface or class in angular. we can do this with the as keyword with a type assertion
let emp:Employee= any type as Employee
The employee is an interface in typescript with id and name fields.
We can also do using generics as seen below.
let emp:Employee= Employee> anytype
import Component, VERSION > from '@angular/core'; import Employee > from '../employee'; @Component( selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] >) export class AppComponent employee: Employee; constructor() this.display( id: 1, name: 'john' >); > display(anyvalue: any) this.employee = anyvalue as Employee; > >
Typescript convert any to number one
“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. —
- you are processing user data (with unreliable types)
- working with data that has changed shape over years (employee code was numeric, now it is alphanumeric :))
- 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. —
- concatenation of a number and string
- convert arrays of numbers to strings for formatting and display
How do I assert types?
There are two ways to do type assertions.
- Bracket syntax. e.g. let length: number = (lengthField);
- 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.