
Typescript
About this quiz
This quiz about Typescript features 10 questions. It was generated by one of our users February 16, 2026.
Welcome to the TypeScript Challenge!
Imagine writing JavaScript code that catches your mistakes before you even run it, provides intelligent autocomplete suggestions, and makes your applications more robust and maintainable. That's the power of TypeScript! Developed by Microsoft and first released in 2012, TypeScript is a "superset" of JavaScript that adds optional static typing to the world's most popular programming language. Think of it as JavaScript with superpowers – every valid JavaScript program is also valid TypeScript, but TypeScript gives you additional tools to write better, more predictable code.
What makes TypeScript truly revolutionary is its ability to catch errors at compile-time rather than runtime. While JavaScript might let you accidentally try to call a method on undefined or pass a string where a number is expected, TypeScript acts like a vigilant code reviewer, spotting these issues before they become bugs in production. Major companies like Microsoft, Slack, Airbnb, and countless others have adopted TypeScript to build large-scale applications with confidence. From simple websites to complex enterprise applications, TypeScript has become the go-to choice for developers who want the flexibility of JavaScript with the safety net of type checking.
Ready to test your TypeScript knowledge? This quiz will challenge your understanding of everything from basic type annotations and interfaces to advanced concepts like generics and utility types. Whether you're a TypeScript newcomer or a seasoned developer, let's see how well you know this game-changing technology that's reshaping modern web development!
TypeScript Complete Study Guide
Table of Contents
- Introduction to TypeScript
- Setting Up TypeScript
- Basic Types
- Variables and Type Annotations
- Functions
- Interfaces
- Classes
- Generics
- Advanced Types
- Modules and Namespaces
- Error Handling
- Best Practices
- Real-World Examples
Introduction to TypeScript
What is TypeScript?
TypeScript is a statically typed superset of JavaScript developed by Microsoft. It adds optional static type checking to JavaScript, helping developers catch errors at compile time rather than runtime.
Why Use TypeScript?
| Advantage | Description |
|---|---|
| Type Safety | Catch errors during development |
| Better IDE Support | Enhanced autocomplete, refactoring, and navigation |
| Code Documentation | Types serve as inline documentation |
| Scalability | Better for large codebases |
| Modern JavaScript | Access to latest ECMAScript features |
TypeScript vs JavaScript
// JavaScript
function greet(name) {
return "Hello, " + name;
}
greet(42); // Runtime error potential
// TypeScript
function greet(name: string): string {
return "Hello, " + name;
}
greet(42); // Compile-time error!
Setting Up TypeScript
Installation
# Global installation
npm install -g typescript
# Project-specific installation
npm install --save-dev typescript
# Using with Node.js
npm install --save-dev @types/node
TypeScript Configuration
Create a tsconfig.json file:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020", "DOM"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Compilation
# Compile a single file
tsc filename.ts
# Compile using tsconfig.json
tsc
# Watch mode
tsc --watch
Basic Types
Primitive Types
// String
let username: string = "John Doe";
let message: string = `Hello, ${username}!`;
// Number
let age: number = 25;
let price: number = 99.99;
let binary: number = 0b1010;
let hex: number = 0xFF;
// Boolean
let isActive: boolean = true;
let isCompleted: boolean = false;
// Undefined and Null
let undefinedValue: undefined = undefined;
let nullValue: null = null;
Array Types
// Array syntax variations
let numbers: number[] = [1, 2, 3, 4, 5];
let fruits: Array<string> = ["apple", "banana", "orange"];
// Mixed arrays (using union types)
let mixed: (string | number)[] = ["hello", 42, "world"];
// Readonly arrays
let readonlyNumbers: readonly number[] = [1, 2, 3];
// readonlyNumbers.push(4); // Error!
Tuple Types
// Basic tuple
let person: [string, number] = ["Alice", 30];
// Named tuple (TypeScript 4.0+)
let coordinate: [x: number, y: number] = [10, 20];
// Optional tuple elements
let response: [string, number?] = ["success"];
// Rest elements in tuples
let scores: [string, ...number[]] = ["Math", 95, 87, 92];
Enum Types
// Numeric enum
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
// String enum
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}
// Mixed enum
enum Status {
Pending = 1,
Success = "success",
Error = "error"
}
// Using enums
let currentDirection: Direction = Direction.Up;
let favoriteColor: Color = Color.Blue;
Any and Unknown Types
// Any type (avoid when possible)
let anything: any = 42;
anything = "hello";
anything = true;
// Unknown type (safer alternative to any)
let userInput: unknown;
userInput = 5;
userInput = "hello";
// Type checking required with unknown
if (typeof userInput === "string") {
console.log(userInput.toUpperCase()); // Safe!
}
Void, Never, and Object Types
// Void - for functions that don't return a value
function logMessage(message: string): void {
console.log(message);
}
// Never - for functions that never return
function throwError(message: string): never {
throw new Error(message);
}
// Object type
let user: object = { name: "John", age: 30 };
// Better object typing
let betterUser: { name: string; age: number } = {
name: "Jane",
age: 25
};
Variables and Type Annotations
Type Inference
// TypeScript infers the type
let inferredString = "Hello"; // string
let inferredNumber = 42; // number
let inferredBoolean = true; // boolean
// Type widening
let flexible = "hello"; // string (can be reassigned to other strings)
const strict = "hello"; // "hello" (literal type)
Type Assertions
// Angle bracket syntax
let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;
// As syntax (preferred in JSX)
let strLength2: number = (someValue as string).length;
// Non-null assertion operator
function processUser(user?: { name: string }) {
// We know user is defined here
console.log(user!.name);
}
Union and Intersection Types
// Union types
type StringOrNumber = string | number;
let value: StringOrNumber = "hello";
value = 42; // Also valid
// Type guards with union types
function processValue(val: string | number) {
if (typeof val === "string") {
return val.toUpperCase(); // TypeScript knows val is string
} else {
return val.toFixed(2); // TypeScript knows val is number
}
}
// Intersection types
type Person = { name: string };
type Employee = { employeeId: number };
type PersonEmployee = Person & Employee;
let worker: PersonEmployee = {
name: "John",
employeeId: 12345
};
Literal Types
// String literal types
type Theme = "light" | "dark" | "auto";
let currentTheme: Theme = "dark";
// Numeric literal types
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 4;
// Boolean literal types
type Success = true;
let isSuccess: Success = true;
// Template literal types (TypeScript 4.1+)
type EventName<T extends string> = `on${Capitalize<T>}`;
type ButtonEvent = EventName<"click">; // "onClick"
Functions
Function Type Annotations
// Function declaration
function add(a: number, b: number): number {
return a + b;
}
// Function expression
const multiply = function(a: number, b: number): number {
return a * b;
};
// Arrow function
const divide = (a: number, b: number): number => a / b;
// Function type
type MathOperation = (a: number, b: number) => number;
const subtract: MathOperation = (a, b) => a - b;
Optional and Default Parameters
// Optional parameters
function greetUser(name: string, title?: string): string {
if (title) {
return `Hello, ${title} ${name}!`;
}
return `Hello, ${name}!`;
}
// Default parameters
function createUser(name: string, role: string = "user"): object {
return { name, role };
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
Function Overloads
// Function overload signatures
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: string | number, b: string | number): string | number {
if (typeof a === "string" && typeof b === "string") {
return a + b;
}
if (typeof a === "number" && typeof b === "number") {
return a + b;
}
throw new Error("Invalid arguments");
}
let result1 = combine("Hello, ", "World!"); // string
let result2 = combine(5, 10); // number
Higher-Order Functions
// Function that returns a function
function createMultiplier(multiplier: number): (value: number) => number {
return (value: number) => value * multiplier;
}
const double = createMultiplier(2);
console.log(double(5)); // 10
// Function that takes a function as parameter
function processArray<T, U>(
array: T[],
processor: (item: T) => U
): U[] {
return array.map(processor);
}
const numbers = [1, 2, 3, 4, 5];
const doubled = processArray(numbers, x => x * 2);
Interfaces
Basic Interfaces
// Interface definition
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
}
// Using the interface
const user: User = {
id: 1,
name: "John Doe",
email: "john@example.com",
isActive: true
};
// Function parameter with interface
function displayUser(user: User): void {
console.log(`${user.name} (${user.email})`);
}
Optional and Readonly Properties
interface Product {
readonly id: number; // Cannot be modified after creation
name: string;
price: number;
description?: string; // Optional property
tags?: string[]; // Optional array
}
const product: Product = {
id: 1,
name: "Laptop",
price: 999.99
};
// product.id = 2; // Error: Cannot assign to 'id' because it is readonly
product.description = "High-performance laptop"; // OK