Working with Strings & Numbers in TypeScript

24 Jun 2023 Balmiki Mandal 0 Typescript

Working with Strings & Numbers in TypeScript

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a typed superset of JavaScript that compiles to plain JavaScript. With TypeScript, developers can use existing JavaScript code, incorporate popular JavaScript libraries, and create new modules. Additionally, it supports other languages such as HTML and CSS. As such, TypeScript provides an array of features for working with strings and numbers.

String Manipulation

One of the primary benefits of TypeScript is its ability to manipulate strings. This includes creating variables, concatenating strings, searching for substrings, and replacing values. To create a string, you can use the following syntax:

let myString:string = "Hello World";

You can also use the "+" operator to join two strings together. For example:

let helloWorldString:string = "Hello" + "World";

TypeScript also supports searching for substrings. This allows you to determine whether a certain value exists within a larger string. This can be accomplished using the indexOf() function as follows:

if (myString.indexOf("World") > -1) {
	// Substring was found
}

Finally, TypeScript also supports replacing values within a string using the replace() function. For example:

let replacedString:string = myString.replace("World", "Universe");

Number Manipulation

TypeScript also provides a variety of features for working with numbers. You can create a number by using the following syntax:

let myNumber:number = 42;

TypeScript provides a wide range of mathematical operations including addition, subtraction, multiplication, and division. This can be accomplished using the "+","-","*" and "/" operators respectively. For example:

let sum:number = myNumber + 10;
let difference:number = myNumber - 10;
let product:number = myNumber * 10;
let quotient:number = myNumber / 10;

TypeScript also supports a variety of functions for working with numbers. This includes rounding numbers, converting between different number types, and generating random numbers. All of these are provided by the Math object which can be used as follows:

let roundedNumber:number = Math.round(myNumber);
let convertedNumber:number = Number(myNumber);
let randomNumber:number = Math.random();

TypeScript is a powerful language that allows developers to work with strings and numbers in ways that would not be possible with plain JavaScript. With TypeScript, developers can quickly create variables, manipulate strings, search for substrings, and perform mathematical operations. As such, TypeScript provides a great way for developers to work with strings and numbers.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.