How do you define a simple function in TypeScript?*You can choose more than one answer
Question
How do you define a simple function in TypeScript?
You can choose more than one answer
Solution
Defining a simple function in TypeScript can be done in the following ways:
- Function Declaration: This is the most common way to define a function in TypeScript. Here is an example:
function greet(name: string): string {
return "Hello, " + name;
}
In this example, greet
is the function name, name
is the parameter with string
as its type, and the function returns a string
.
- Function Expression: This is another way to define a function in TypeScript. Here is an example:
let greet = function(name: string): string {
return "Hello, " + name;
};
In this example, a function is assigned to the variable greet
. The function takes one parameter name
of type string
and returns a string
.
- Arrow Function: This is a more modern way to define a function in TypeScript. Here is an example:
let greet = (name: string): string => {
return "Hello, " + name;
};
In this example, an arrow function is assigned to the variable greet
. The function takes one parameter name
of type string
and returns a string
.
Remember, TypeScript is a statically typed superset of JavaScript, so it adds static types to the functions, which helps in better code structuring and error checking.
Similar Questions
True or False: In TypeScript, you can assign a value of type string to a variable of type number.
Can you identify and correct it?function greet(name: string) { console.log("Hello, " + name);}greet(123);What is the error, and how would you correct it?
Explain the following concepts! (9 points)a) Type declaration file (in TypeScript)b) Transpilerc) Static typing
How can you use TypeScript with tools like TypeScript Playground for quick experimentation?
What will be the output of the following TypeScript code?let i = 0;do { i++;} while (i < 3);console.log(i);*1 point0123
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.