TypeScript - Notes
What is TypeScript?
TypeScript is a superset of JavaScript, adding static typing and
other features to improve development efficiency and safety.
It compiles to JavaScript and works anywhere JavaScript does
(browsers, Node.js).
TypeScript vs. JavaScript
Feature JavaScript TypeScript
Typing Dynamically typed Statically typed
Good, limited type-
Tooling Support Excellent with powerful tooling
checking
Debugging
Caught at runtime Caught at compile-time
Errors
Code Explicit types, better
Simple, lacks type info
Readability documentation
Example:
JS: function greet(name) { return "Hello, " + name.toUpperCase(); }
TS: function greet(name: string): string { return "Hello, " +
name.toUpperCase(); }
TS/JS Interoperability
TypeScript works seamlessly with JavaScript.
Example: Import JavaScript in TypeScript.
Installing and Configuring TypeScript
1. Install: npm install -g typescript
2. Initialize a project: tsc --init (creates tsconfig.json).
Running TypeScript
Compile to JS: tsc file.ts
Run directly: npx ts-node file.ts
Test in Playground: Use TypeScript Playground.
TypeScript Types
Primitive Types:
o boolean, number, string, void, undefined, null.
Object Types:
o Interfaces: Define object structure (e.g., interface User
{ name: string; age: number; }).
o Classes: Define properties and methods (e.g., class Car
{ make: string; model: string; }).
o Enums: Define named constants (e.g., enum Days { Sunday,
Monday, Tuesday }).
o Arrays and Tuples: (e.g., let numbers: number[] = [1, 2, 3]; and
let tuple: [string, number] = ["Alice", 25];).
Other Types:
o any, unknown, never, object, and Type Assertions.
Combining Types
Union Types: Combine multiple types (e.g., let id: number | string;).
Intersection Types: Combine types (e.g., type Staff = Person &
Employee;).
Type Aliases: Create shorthand for types (e.g., type ID = number |
string;).
keyof Operator: Get keys of a type (e.g., type UserKeys = keyof
User;).
Type Guards
Used to narrow types during runtime.
Example: if (typeof input === "string")
{ console.log(input.toUpperCase()); }
TypeScript Functions
Function Typing: Define types for parameters and return values.
Function Overloading: Define multiple signatures (e.g., function
greet(input: string | string[]): string).
TypeScript Interfaces
Type vs. Interface: Interfaces are ideal for object shapes, while
types are used for functions, unions, and primitives.
Extending Interfaces: Combine interfaces (e.g., interface Dog
extends Animal { breed: string; }).
Declaration Merging: Same-named interfaces merge properties.
Classes
Constructor Parameters: Define and initialize properties in
constructor (e.g., class User { constructor(public name: string,
private age: number) {}).
Examples:
1. TypeScript vs. JavaScript
JavaScript (Dynamic Typing):
function greet(name) {
return "Hello, " + name.toUpperCase();
}
TypeScript (Static Typing):
function greet(name: string): string {
return "Hello, " + name.toUpperCase();
}
2. TS/JS Interoperability
JavaScript file (math.js):
export function add(a, b) {
return a + b;
}
TypeScript file (main.ts):
import { add } from './math';
console.log(add(2, 3)); // Output: 5
3. TypeScript Types
Primitive Types:
let isActive: boolean = true;
let age: number = 25;
let username: string = "Alice";
let undefinedValue: undefined = undefined;
let emptyValue: null = null;
Object Types (Interfaces):
interface User {
name: string;
age: number;
}
const user: User = { name: "John", age: 30 };
Enums:
enum Direction {
North,
South,
East,
West
}
let dir: Direction = Direction.North;
console.log(Direction[dir]); // Output: North
Arrays and Tuples:
let numbers: number[] = [1, 2, 3];
let tuple: [string, number] = ["Alice", 25];
4. Combining Types
Union Types:
let id: number | string;
id = 42; // Valid
id = "123"; // Valid
Intersection Types:
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type Staff = Person & Employee;
const staff: Staff = { name: "Alice", employeeId: 1 };
5. Type Guards
Typeof and Instanceof:
let input: unknown = "hello";
if (typeof input === "string") {
console.log(input.toUpperCase()); // Output: HELLO
}
let obj: any = new Date();
if (obj instanceof Date) {
console.log("It's a date!"); // Output: It's a date!
}
6. TypeScript Functions
Typing Functions:
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 10)); // Output: 15
Function Overloading:
function greet(name: string): string;
function greet(names: string[]): string;
function greet(input: any): string {
if (typeof input === "string") {
return `Hello, ${input}!`;
} else if (Array.isArray(input)) {
return `Hello, ${input.join(", ")}!`;
}
return "";
}
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet(["Alice", "Bob"])); // Output: Hello, Alice, Bob!
7. TypeScript Interfaces
Defining an Interface:
interface Person {
name: string;
age: number;
}
const person: Person = { name: "Snehal", age: 18 };
function greet(person: Person) {
console.log(`Hello, ${person.name}! You are ${person.age} years
old.`);
}
greet(person); // Output: Hello, Snehal! You are 18 years old.
Extending Interfaces:
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const myDog: Dog = { name: "Buddy", breed: "Golden Retriever" };
console.log(myDog); // Output: { name: 'Buddy', breed: 'Golden
Retriever' }
Interface Declaration Merging:
interface Person {
name: string;
}
interface Person {
age: number;
}
const individual: Person = { name: "Alice", age: 30 };
console.log(individual); // Output: { name: 'Alice', age: 30 }
8. Classes in TypeScript
Constructor Parameters:
class User {
constructor(public name: string, private age: number) {}
}
const user = new User("Alice", 25);
console.log(user.name); // Output: Alice
// console.log(user.age); // Error: 'age' is private
Mcq examples:
1. Which of the following is the correct way to define a variable in
TypeScript?
A) let name: string = "John";
B) let name = "John";
C) var name: string = "John";
D) const name: string = "John";
2. How do you define a function with two arguments, one of type
string and the other of type number, in TypeScript?
A) function myFunc(a: string, b: number): void {}
B) function myFunc(a: string, b: number) {}
C) function myFunc(a: string, b) {}
D) function myFunc(string, number) {}
3. What does TypeScript provide that JavaScript doesn't?
A) Static type checking
B) Dynamic typing
C) Object-oriented programming features
D) Functional programming capabilities
4. Which of the following is NOT a valid TypeScript data type?
A) number
B) string
C) boolean
D) character
5. Which keyword is used to define an interface in TypeScript?
A) interface
B) struct
C) type
D) class
6. How do you declare a tuple in TypeScript?
A) let myTuple = [1, "John"];
B) let myTuple: [number, string] = [1, "John"];
C) let myTuple: Tuple<number, string> = [1, "John"];
D) let myTuple: (number, string) = [1, "John"];
7. Which of the following is the correct type annotation for an array
of strings?
A) string[]
B) Array<string>
C) string[] | Array<string>
D) Array[str]
8. How do you define a function type in TypeScript?
A) let func: (a: number, b: string) => void;
B) let func: (number, string) => void;
C) let func: (number, string) -> void;
D) let func: (a: number, b: string) -> void;
9. Which keyword is used to define a class in TypeScript?
A) class
B) function
C) object
D) type
10. How do you define a readonly array in TypeScript?
A) let arr: readonly number[];
B) let arr: number[] readonly;
C) let arr: number[]; readonly
D) let arr: readonly[1,2,3];
11. Which of the following is correct syntax for a TypeScript enum?
A) enum Colors {Red, Green, Blue}
B) enum Colors {Red = 1, Green = 2, Blue = 3}
C) enum Colors {Red, Green, Blue = 3}
D) All of the above
12. Which operator is used to declare a type alias in TypeScript?
A) =>
B) :=
C) =
D) ::
13. What is the correct way to make a property optional in an
interface?
A) name: string?;
B) name: string[];
C) name?: string;
D) name: Optional<string>;
14. How do you explicitly define the return type of a function in
TypeScript?
A) function foo(): string {}
B) function foo(): number {}
C) function foo(): void {}
D) function foo(): boolean {}
15. Which of the following TypeScript features provides better code
reuse?
A) Generics
B) Classes
C) Functions
D) Constants
16. What will be the type of x after the following TypeScript code
executes?
let x: any = 5;
x = "Hello";
A) any
B) string
C) number
D) unknown
17. What does the unknown type in TypeScript signify?
A) It is a type that can accept any value but requires checking before
using.
B) It is the same as any, but with fewer restrictions.
C) It can only accept null or undefined values.
D) It is a way to mark variables that are not initialized.
18. What is the purpose of the as keyword in TypeScript?
A) To perform type assertion
B) To define a type
C) To perform type coercion
D) To declare a variable
19. Which type of variable does TypeScript infer from the following
code?
let x = 10;
A) number
B) any
C) undefined
D) unknown
20. What happens if you try to access a property that doesn't exist
on a TypeScript object?
A) TypeScript throws a compile-time error.
B) TypeScript throws a runtime error.
C) TypeScript returns undefined.
D) TypeScript throws a null error.