You are reading the article Learn How To Implement Promise In Typescript? updated in November 2023 on the website Bellydancehcm.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 Learn How To Implement Promise In Typescript?
Introduction to TypeScript promiseThe promise in TypeScript is used to make asynchronous programming. The promise can be used when we want to handle multiple tasks at the same time. By the use of TypeScript promise, we can skip the current operation and move to the next line of the code. Promise provides the feature for asynchronous programming or parallel programming, which allows the number of tasks to be executed simultaneously at the same time. In the coming section, we will discuss more the promise in detail for better understanding.
Syntax
As we discussed, a promise is used for parallel programming. It is an object available in TypeScript programming. Let’s see its syntax in detail for better understanding see below;
new Promise(function(resolve, reject){ });As you can see in the above lines of syntax, we are using a new keyword to create the object of promise. This function has two parameters named reject and resolve. It also calls the callback function. We will see its internal working in more detail in the coming section and use it while programming.
How to implement promise in TypeScript?As we know that promise in TypeScript is used to support parallel programming. Parallel programming is used when we want to execute a set of tasks simultaneously. The promise is used to handle multiple parallel calls. The main benefit of using the promise is that we can move to the next line of the code without executing the above line. This also helps us to increase the performance of the application.
Promise support in several states as well. In this section, we will look at the signature in detail also the return type, and the several states it supports for better understanding. See below;
1. new Promise(function(resolve, reject){
// logic goes here ..
});
In the above line of code, we are using the ‘new’ keyword to create the instance of the promise. As we already know that this is an object available in TypeScript. Also, it has one inner function, which has two parameters named ‘reject’ and ‘resolve’. Inside this function, we can pass a callback function.
2. Return type: It has two parameters inside the inner function. If the function’s response is a success, then it will return ‘resolve’; if the response from the function is not successful, it will return ‘reject’.
3. States available in promise of Typescript: Promise support several states. These states are used to get the status of the function. We have three different states available in the promise;
reject: If the response from the promise function fails, then the state would be ‘reject’.
pending: We the response does not come, and we are waiting for the result, then the state would be ‘pending’.
fulfilled: If the response forms the promise in TypeScript is received successfully, then the state would be ‘fullfeed’.
We can also perform and handle the success and error response, respectively. For this, we can use ‘reject’ and ‘resolve’ from the promise function only. In this section, we will cover how to handle the success and error in promise see below;
1. Handle error in the promise: We can easily handle the error response from a promise, for we have to reject parameter that we pass inside the callback function. This rejects parameter will handle the error; it will handle the error using the catch() block available. We can see one practice syntax for better understanding of its usage see below;
Example:
function demo() { reject(); } demo().then(function(success) { }) .catch(function(error) { });As you can see in the above lines of code, we are calling reject. This will handle the error and handle the exception using the catch block in the below line of code.
2. handle success in the promise: We can also handle the success response from the promise function. For this, we can use resolve and a success callback. Let’s see one sample syntax for a better understanding of the code for beginners see below;
Example:
function demo() { resolve(); } demo().then( );In the above lines of code, we are calling the resolve function here; it will handle the success response from the promise function in TypeScript.
ExamplesHere are the following example mention below
Example #1In this example, we are trying to call the resolve function of promise, which will handle the successful response from the promise. This is a sample example for beginners to understand its usage.
Code:
console.log("Demo to show promise in Typescript !!"); resolve(100); });Output:
Example #2In this example, we are handling the error response from the promise in Typescript, a sample example for beginners.
Code:
console.log("Demo to show promise in Typescript !!"); reject("this is an reject response form the promise !!!!"); });Output:
Rules and regulations for the promise1. This is used to make asynchrony calls.
2. keep in mind that only tasks that are not dependent on each other can be called from. Otherwise, the data inconsistent issue will occur.
3. Need to pass inner function while using it; otherwise, the error will occur.
ConclusionBy using promise in TypeScript, we can easily implement parallel programming, which is very easy to read and understand. Also, by the use of it, we can execute multiple tasks at the same time; this can also increase the application performance. The only task which is not dependent on each other can be asynchrony.
Recommended ArticlesWe hope that this EDUCBA information on “TypeScript promise” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
You're reading Learn How To Implement Promise In Typescript?
Learn How Object Work In Typescript?
Introduction to TypeScript object
object in TypeScript is used to represent the key-value pair form. By the use of objects, we can create a key and assign it to a value, if we have any small object which we want to handle without creating any model or POJO class in TypeScript then we can go for the object. They are handy to use and easy to understand. We can create objects by using different types, also they are like any other variable we declare and use in TypeScript. In the coming section, we will discuss more objects in detail to explore their usage while doing programming to make them more efficient.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
var your_object__name = { key1: "value1", key2: "value2", key3: "value3", so on.... }As you can see in the above lines of syntax we are just creating a simple variable and inside it, we are assigning its value as key value pair. Let’s see one practice syntax for clarity see below;
e.g. :
var demo = { key1: "100", key2: "200", key3: "300" }In the coming section, we will discuss more its internal working and declaration of other types inside objects in more detail.
How object works in TypeScript?As we already know that object is just like declaring any other variable in TypeScript. But we have one difference here is that we can assign a key for our variable inside the object. This makes them easy to use. After the creation of the object, we can access them by using the ‘key’ name. Also inside the object in TypeScript, we can easily call our function, declare an array, also another object, etc. It is not mandatory that we can only specify the string or number type only it supports everything from TypeScript. This object is like the POJO classes of java which holds the data from entity or request elements. In TypeScript, we create a model for that, but if we have a small object which we want to use within one class only then we can go for the object in TypeScript.
Let’s try to declare functions, arrays and another object inside the existing object in TypeScript see below.
1) Functions: We can declare our functions inside it, like any other values we are declaring see below.
Code:
functionObject = { key1: function() { }, };In the above lines of code, we are using a function inside the object. This is a very simple syntax to remember.
2) Array: Also we can declare an array inside the object instance like below;
Code:
var arrayObject = { key1:["val1", "val2", "val3" .. so on ] };In the above lines of code, we declare an array inside the object instance, very easy and simple to use. After this, we can access this array by its key name.
Access of object values:
To access values inside the object we can directly use their name. But make sure it is correct and present inside the object otherwise it will give an error at runtime. Let’s take the example below;
Code:
var myobject = { key1: "100" }; let result = myobject.key1; Types of objectIn TypeScript we can define objects by using different types available which are as following see below;
1) Type alias: We can use ‘type’ alias to define or declare our object in TypeScript, they are another type of object in TypeScript. Let’s see its syntax and how to use and create in TypeScript;
syntax:
type Object_name = { };As you can see in the above lines of code, we are using ‘type’ keyword just before the object name to make it work like Type alias in TypeScript, inside this, we can define our member variable which can be anything or any type.
Code:
type Demo = { rollno: number; city: string; name: string; };2) Use interface: We can also use an interface to define our object in typescript, this is another type of declaring object in TypeScript. Let’s see its syntax for better understanding;
syntax:
interface object_name { }As you can see in the above lines of code we are using the ‘interface’ keyword just before the object name to make it work like an object in TypeScript, inside this, we can define our variables or member variable.
Code:
interface Demo = { rollno: number; city: string; name: string; }; ExamplesCode:
var myobject = { key1:"One", key2:"Two" , key3:"three" , key4:"four" , key5:"five " }; console.log("Printdemo to show object in Typescript") console.log("Print the objects values :::") let result1 = myobject.key1 console.log("result one is ::" + result1) let result2 = myobject.key2 console.log("result two is ::" + result2) let result3 = myobject.key3 console.log("result three is ::" + result3) let result4 = myobject.key4 console.log("result four is ::" + result4) let result5 = myobject.key5 console.log("result five is ::" + result5)Output:
Rules and Regulations for objectThere is as such no rules or restriction for objects but we have some standard that needs to be followed see below;
1) Every new value should be separated with ‘,’ each after one another.
2) Object should be surrounded with ‘{}’ braces.
3) To access the values we can use their key as references.
4) Key should be present in the object before using them otherwise it will throw runtime error saying ‘unknown property’
Conclusion – TypeScript objectAs we now know objects are very easy to use and can replace model objects if not necessary. We have also discussed the object types in detail as well. To use them only a keyword has to be used before the object name.
Recommended ArticlesThis is a guide to TypeScript object. Here we discuss How object works in TypeScript along with the types and Examples. You may also have a look at the following articles to learn more –
Learn Various Methods Of Typescript Array
Introduction to TypeScript Array
Suppose you have seen, we know that there are many data types. We can divide them as primitive and user-defined. The array comes under a user-defined data type. All the programming languages have an array as their data type. So the same concept we have in typescript. The general definition of an array is a collection of homogeneous data items in a single element. We all are familiar with the word array if you are from the computer world. So let’s take a deep dive into that.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
How to Declare an Array in TypeScript?Like Java, we have multiple ways to write arrays in TypeScript.
Syntax #1:
let colors: string[] = ["DourgerBlue", "NavyBlue", "SkyBlue"]; console.log(colors)Output:
In the above example, we declared one variable with the let keyword of type string, and after that, we have given square brackets, which shows us it is a type of array. After that, it is an equal (=) sign, and we gave the values in square brackets separated by commas.
Syntax #2:
Now, in this type, we are explicitly writing an array.
console.log(colors[0]); console.log(colors[1]); console.log(colors[2]);
Output:
In the above example, we gave the let keyword with the variable name after that colon(:) and specified the data type as an array, and the array type is a string.
We have different syntax in both of the above examples. You can use them interchangeably. There are some common steps to understand further. In the coming session, we will see what initializing arrays mean.
How to Initialize an array in TypeScript?In the above two examples of syntax, we have seen that both declaration and initialization have been done simultaneously in a single line. Let’s scatter them and see how they will be implemented actually.
Syntax #1 let colors: string[];Initializing array
colors = ['DourgerBlue', 'NavyBlue', SkyBlue]; Syntax #2Declaring array
Initializing array
colors = ['DourgerBlue', 'NavyBlue', SkyBlue];We can declare and initialize the array separately or can be in the same line in a combined manner also.
It is just a matter of syntax and style of programming we need.
How to Access Array Elements?Till now, we know how to declare and initialize the array. Now here comes the main part. In Programming, of course, we need to do some operations. Performing some operations on array elements, we need to access them. To access these elements, we need to understand their structure of it.
As we know, we can store multiple elements in a single variable. But those elements get identified by one unique number starting from zero(0). These numbers are known as the index no of an array element.
To be more precise, consider the int array containing 5 nos.
let toffee: number [] = [1,2,3,4,5];Let’s see if it is a memory representation to access the array elements.
In the above diagram, we have index no. With the help of these indexes no, we can access a particular element in an array.
Example:
let toffee: number [] = [1,2,3,4,5]; console.log(toffee[0]); console.log(toffee[1]); console.log(toffee[2]); console.log(toffee[3]); console.log(toffee[4]);Output:
Logging this to the console will give you the desired output.
Various Methods of Typescript ArrayThere are some predefined methods in the array which help us to get output efficiently. Following is the list of these methods.
filter(): This function mainly works when you want to modify the existing array and create a new one. It will transform the existing values with the new condition.
every(): This function is mainly used for testing purposes. It checks for every element in an array that is true or not.
forEach(): This works similarly to for loop but works on each element in the array.
concat(): As the name suggests, it concretes the array values of two different arrays and returns a new array.
indexOf(): As we have seen, that array has an index value. This method returns the index of an element in an array.
lastIndexOf(): As we know array has no elements. This method gives a maximum index value of the array. Nothing but the index no of the last value in the array.
join(): This method joins all array elements and returns with a specified separator.
push(): If you have worked with an array earlier, you must know about this method. This method adds one or more elements to the array at the last of the array.
map(): This function returns the new array. And this new array is the output of the condition provided in the map.
pop(): This method is used to get an array’s last element and remove it from the array.
reverse(): As the name suggests, it simply makes the array in reverse format.
reduceRight(): It applies to the array to reduce the array elements from the right. /it reduces the given array to a single value.
reduce(): It works the same as the above function reduceRight. But in the opposite direction.
shift(): It is the opposite of pop; it removes the first element from an array. It returns the removed elements.
slice(): We can take a piece from an array and return that new array by this function.
splice(): With this method, we can add or remove an array element.
sort(): Sorting of array elements implemented by this function.
some(): In the testing scenario, returns true if at least one condition is true.
unshift(): This method helps to add elements at the start of the array and return a new array.
toString(): It converts the array elements to string and returns it.
Recommended ArticlesThis is a guide to TypeScript Array. Here we discuss how to Initialize an array in TypeScript? and the Various Methods of Typescript Array along with Outputs. You can also go through our other related articles to learn more–
Guide To How To Implement Array_Agg()
Introduction to PostgreSQL ARRAY_AGG()
The PostgreSQL provides various aggregate functions; the PostgreSQL ARRAY_AGG() aggregate function is used to get an array with each value of the input set added to an array element. This aggregate Function accepts a set of values as input, and the Function includes NULL values into the array while concatenating the input values. We use the ORDER BY clause with this aggregate Function in order to sort the result.
Start Your Free Data Science Course
Hadoop, Data Science, Statistics & others
Consider the following syntax of the PostgreSQL ARRAY_AGG() aggregate Function:
ARRAY_AGG(): The PostgreSQL ARRAY_AGG() aggregate Function takes the number of values as an input and then returns an array.
ORDER BY: This is an optional clause. This clause is used when we want the results sorted, which are processed in the aggregation, which results to sort the elements in the result array.
Examples to Implement PostgreSQL ARRAY_AGG()We will create two tables of name ‘student’ and ‘department’ by using the CREATE TABLE statement as follows to understand the examples:
create table student ( stud_id serial PRIMARY KEY, stud_fname VARCHAR(80) NOT NULL, stud_lname VARCHAR(80) NOT NULL, department_id int NOT NULL ); create table department ( department_id serial PRIMARY KEY, department_name VARCHAR(80) NOT NULL );We will insert data into the department table using the INSERT INTO statement as follows.
INSERT INTO department(department_name) VALUES ('Computer'), ('Electrical'), ('IT'), ('Civil'), ('Chemical'), ('Mechanical');Illustrate the result of the above INSERT INTO statement by using the following SQL statement and snapshot.
Code:
select * from department;Output:
We will insert some data into the student table using the INSERT INTO statement as follows.
INSERT INTO student(stud_fname, stud_lname, department_id) VALUES ('Smith','Johnson',1), ('Williams','Jones',1), ('Harper','James',2), ('Jack','Liam',2), ('Harry','Mason',3), ('Jacob','Oscar',3), ('Michael','Charlie',4), ('William','Joe',4), ('Oliver','John',5), ('Jack','Richard',5), ('Harry','Joseph',5), ('George','Thomas',6), ('Brown','Charles',6);Illustrate the result of the above INSERT INTO statement by using the following SQL statement and snapshot.
Code:
select * from student;Output:
Example #1Without ORDER BY clause in PostgreSQL ARRAY_AGG, () aggregate Function Consider the following SQL statement, which will use the Function to return the list of names of the department and the list of names of the students studying in each department:
Code:
SELECT department_name, FROM department INNER JOIN student USING (department_id) GROUP BY department_name ORDER BY Department_name;Illustrate the result of the above SQL statement by using the following snapshot.
From the above example, we can see that each department’s students are randomly ordered; to sort the students by their last name or first name, we have to define the ORDER BY clause in this Function.
Example #2ORDER BY clause with PostgreSQL ARRAY_AGG() aggregate Function
Consider the following example to get the list of students for each department, which is sorted by the student’s first name as shown in the following SQL statement:
Code:
SELECT department_name, ARRAY_AGG ( ORDER BY stud_fname ) students FROM department INNER JOIN student USING (department_id) GROUP BY department_name ORDER BY department_name; Example #3ORDER BY clause with PostgreSQL ARRAY_AGG() aggregate Function
Consider the following example to sort the list of students for each department by student’s first and last name, as shown in the following SQL statement:
Code:
SELECT department_name, ARRAY_AGG ( ORDER BY stud_fname ASC, stud_lname DESC ) student FROM department INNER JOIN student USING (department_id) GROUP BY department_name ORDER BY department_name;Illustrate the result of the above SQL statement by using the following snapshot.
ConclusionFrom the above article, we hope you understand how to use the PostgreSQL ARRAY_AGG() aggregate Function and how the aggregate Function works. Also, we have added several examples of aggregate functions to understand them in detail.
Recommended ArticlesWe hope that this EDUCBA information on “PostgreSQL ARRAY_AGG()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Learn How To Install Smplayer In Ubuntu
SMPlayer is a free media player for windows and Linux with built-in codecs, which will additionally play YouTube videos, search and down load subtitles, and entails other points like a thumbnail generator and audio and video filters.
Features
Help for Youtube. That you can search, play and down-load Youtube movies
Many video and audio filters are available
Thumbnail generator
Video equaliser
It has many Skins/Themes
It supports a couple of speed playback
It supports audio and subtitles delay adjustment
Installing SMPlayerTo install SMPlayer, add the following PPA on Ubuntu−
$sudo add-apt-repository ppa:rvm/smplayerThe sample output should be like this −
Packages for SMPlayer. To install SMPlayer from this PPA, run these commands on a terminal: sudo add-apt-repository ppa:rvm/smplayer sudo apt-get update sudo apt-get install smplayer smtube smplayer-themes smplayer-skins Press [ENTER] to continue or ctrl-c to cancel adding it gpg: keyring `/tmp/tmpeab9bvoh/secring.gpg' created gpg: keyring `/tmp/tmpeab9bvoh/pubring.gpg' created gpg: chúng tôi trustdb created gpg: key E4A4F4F4: public key "Launchpad PPA named smplayer for rvm" imported gpg: no ultimately trusted keys found gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1) OKNow update the packages by using the following command −
$sudo apt-get update .................................................................................................To install SMplayer with skins, use the following command −
$ sudo apt-get install smplayer smplayer-themes smplayer-skinsThe sample output should be like this −
Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: esound-common libaudiofile1 libdirectfb-1.2-9 libenca0 libesd0 libgif7 libqt4-opengl libqtwebkit4 libsdl1.2debian libvorbisidec1 mplayer smtube Suggested packages: The following NEW packages will be installed: esound-common libaudiofile1 libdirectfb-1.2-9 libenca0 libesd0 libgif7 libqt4-opengl libqtwebkit4 libsdl1.2debian libvorbisidec1 mplayer smplayer smplayer-skins smplayer-themes smtube 0 upgraded, 15 newly installed, 0 to remove and 284 not upgraded. Need to get 18.9 MB of archives. After this operation, 66.8 MB of additional disk space will be used. Do you want to continue? [Y/n] y .................................................................................To open SMplayer, use the following command −
$ smplayer Usage: smplayer [-minigui] [-defaultgui] [-mpcgui] [-config-path directory] [-send-action action_name] [-actions action_list] [-close-at-end] [-no-close-at-end] [-fullscreen] [-no-fullscreen] [-ontop] [-no-ontop] [-sub subtitle_file] [-pos x y] [-size width height] [-add-to-playlist] -minigui: opens the mini gui instead of the default one. -mpcgui: opens the mpc gui. -defaultgui: opens the default gui. -skingui: opens the gui with support for skins. -config-path: specifies the directory where smplayer will store its configuration files (smplayer.ini, smplayer_files.ini...) -send-action: tries to make a connection to another running instance and send to it the specified action. Example: -send-action pause The rest of options (if any) will be ignored and the application will exit. It will return 0 on success or -1 on failure. -actions: action_list is a list of actions separated by spaces. The actions will be executed just after loading the file (if any) in the same order you entered. For checkable actions you can pass true or false as parameter. Example: -actions "fullscreen compact true". Quotes are necessary in case you pass more than one action. -close-at-end: the main window will be closed when the file/playlist finishes. -no-close-at-end: the main window won't be closed when the file/playlist finishes. -fullscreen: the video will be played in fullscreen mode. -no-fullscreen: the video will be played in window mode. -ontop: sets the stay on top option to always. -no-ontop: sets the stay on top option to never. -sub: specifies the subtitle file to be loaded for the first video. -media-title: sets the media title for the first video. -pos: specifies the coordinates where the main window will be displayed. -size: specifies the size of the main window. -help: will show this message and then will exit. -add-to-playlist: if there's another instance running, the media will be added to that instance's playlist. If there's no other instance, this option will be ignored and the files will be opened in a new instance. media: 'media' is any kind of file that SMPlayer can open. It can be a local file, a DVD (e.g. dvd://1), an Internet stream (e.g. mms://....) or a local playlist in format m3u or pls.After this article, you will be able to understand how to install SMPlayer in Ubuntu. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
Source: SMPlayer Portal
Find Hypotenuse Of A Number In Typescript
The longest side of a right-angled triangle and the side that faces away from the right angle is known as the Hypotenuse. The Pythagorean theorem explains that the Hypotenuse’s square equals the sum of the squares of the other two sides. We can be used to determine it using this theorem. The formula representation for this theorem is c2 = a2 + b2, where c means the Hypotenuse and a and b are the triangle’s two sides. When the lengths of the other two sides of a triangle are known, the Pythagorean theorem quickly determines the value of the Hypotenuse. First, we have to take the square root of the sum of the squares on the other two sides to obtain the Hypotenuse.
The Pythagorean theorem can be used to compute the Hypotenuse in TypeScript by writing a function that accepts the lengths of the two shorter sides as parameters. As a result, the function returns the Hypotenuse. There is a condition to apply this theorem and find the Hypotenuse. The triangle must be a right triangle for this function to work, necessitating that one of the angles must be a right angle (90 degrees). The Pythagorean theorem cannot be applied to determine the Hypotenuse if the triangle is not a right triangle. We will be describing the function of typescript using two examples.
SyntaxThe function can be defined as follows −
function hypotenuse(a: number, b: number): number { return Math.sqrt(a * a + b * b); }This function takes two arguments, a and b, representing the lengths of the two shorter sides of the triangle. It then calculates the square of the hypotenuse by adding the squares of a and b and finally returns the square root of that sum.
It’s important to note that this function assumes that the triangle is a right triangle, meaning that one of the angles is a right angle (90 degrees). If the triangle is not a right triangle, the Pythagorean theorem cannot be used to find the hypotenuse.
ExampleIn this example, we will find the hypotenuse of a number in TypeScript. The following steps need to be performed, and the explanations are also given below −
Steps
We first define a function called hypotenuse that takes two arguments, a and b, which represent the lengths of the two shorter sides of the triangle. This function uses the Pythagorean theorem to calculate the square of the hypotenuse by adding the squares of a and b and then returns the square root of that sum using the Math.sqrt() method in TypeScript.
Then we define two variables, side1, and side2, which are the two shorter sides of the triangle. These values are assigned as 3 and 4, respectively.
Then we call the hypotenuse function by passing side1 and side2 as arguments, and the result is stored in a variable hypotenuseValue.
Finally, we use the console.log() method to print the result in the console.
function hypotenuse(a: number, b: number): number { return Math.sqrt(a * a + b * b) } let side1: number = 3 let side2: number = 4 let hypotenuseValue: number = hypotenuse(side1, side2) console.log( `The hypotenuse of the triangle with sides ${side1} and ${side2} is ${hypotenuseValue}.` )On compiling, it will generate the following JavaScript code −
function hypotenuse(a, b) { return Math.sqrt(a * a + b * b); } var side1 = 3; var side2 = 4; var hypotenuseValue = hypotenuse(side1, side2); console.log("The hypotenuse of the triangle with sides " + side1 + " and " + side2 + " is " + hypotenuseValue + "."); OutputThe above code will produce the following output –
The hypotenuse of the triangle with sides 3 and 4 is 5. ExampleIn this example, we will find the hypotenuse of a number using the chúng tôi and chúng tôi methods in TypeScript. The following steps need to be performed, and the explanations are also given below −
Steps
We have created a function called findHypotenuse that takes two arguments, a and b, which represent the lengths of the two shorter sides of the triangle.
Inside the function, we use the Math.pow(base, exponent) method to square the values of a and b and then use the Math.sqrt() method to find the square root of the sum of the squares of a and b. This will give us the hypotenuse of the triangle.
Then we define two variables, side A and side B, which are the two shorter sides of the triangle. These values are assigned as 5 and 12, respectively.
We then call the findHypotenuse function by passing sides A and B as arguments, and the result is stored in a variable hypotenuse.
function findHypotenuse(a: number, b: number): number { return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)) } let sideA: number = 5 let sideB: number = 12 let hypotenuse: number = findHypotenuse(sideA, sideB) console.log( `The hypotenuse of the triangle with sides ${sideA} and ${sideB} is ${hypotenuse}.` )On compiling, it will generate the following JavaScript code −
function findHypotenuse(a, b) { return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); } var sideA = 5; var sideB = 12; var hypotenuse = findHypotenuse(sideA, sideB); console.log("The hypotenuse of the triangle with sides " + sideA + " and " + sideB + " is " + hypotenuse + "."); OutputThe above code will produce the following output –
The hypotenuse of the triangle with sides 5 and 12 is 13.Using TypeScript, we can even perform more mathematical calculations efficiently. Finding hypotenuse is one example of it. Also, the results are fast and accurate.
Update the detailed information about Learn How To Implement Promise In Typescript? on the Bellydancehcm.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!