0
0
Typescriptprogramming~5 mins

Declaring functions and classes in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
How do you declare a simple function in TypeScript that adds two numbers?
You declare it using the <code>function</code> keyword, specify parameter types, and return type. Example:<br><pre>function add(a: number, b: number): number {<br>  return a + b;<br>}</pre>
Click to reveal answer
beginner
What is the syntax to declare a class with a constructor in TypeScript?
Use the <code>class</code> keyword, define a <code>constructor</code> method to initialize properties. Example:<br><pre>class Person {<br>  name: string;<br>  constructor(name: string) {<br>    this.name = name;<br>  }<br>}</pre>
Click to reveal answer
beginner
What does the <code>this</code> keyword refer to inside a class method?
this refers to the current instance of the class, allowing access to its properties and other methods.
Click to reveal answer
intermediate
How do you declare a function expression with a type annotation in TypeScript?
You can assign a function to a variable with a type. Example:<br><pre>const multiply: (x: number, y: number) => number = (x, y) => x * y;</pre>
Click to reveal answer
intermediate
What is the difference between a function declaration and a function expression in TypeScript?
A function declaration is hoisted and can be called before it is defined. A function expression is assigned to a variable and is not hoisted, so it must be defined before use.
Click to reveal answer
Which keyword is used to declare a class in TypeScript?
Aclass
Bfunction
Cobject
Dstruct
What is the correct way to specify the return type of a function that returns a string?
Afunction greet(): String {}
Bfunction greet(): string {}
Cfunction greet(): str {}
Dfunction greet() -> string {}
How do you access a property named age inside a class method?
Athis.age
Bself.age
Cage
Dclass.age
Which of the following is a valid function expression in TypeScript?
Alet f = (x) => x * 2;
Bfunction f(x: number): number { return x * 2; };
Cconst f = function(x: number): number { return x * 2; };
Dvar f: function = (x) => x * 2;
What happens if you call a function expression before it is defined?
AIt works fine because all functions are hoisted.
BIt calls the function but with default parameters.
CIt returns undefined.
DIt causes an error because function expressions are not hoisted.
Explain how to declare a class with a constructor and a method in TypeScript.
Think about how you create a blueprint for objects with properties and actions.
You got /5 concepts.
    Describe the difference between function declarations and function expressions in TypeScript.
    Consider when you can call the function in your code relative to where it is written.
    You got /4 concepts.