Here’s a quick 20-minute tutorial to help you learn the basics of TypeScript. TypeScript is a superset of JavaScript that adds static typing and some useful features to help you write safer and more maintainable code. It assumes you are familiar with basic JavaScript concepts.
1. What is TypeScript? (2 minutes)¶
- TypeScript extends JavaScript by adding types. This helps catch errors during development instead of at runtime.
- TypeScript code needs to be compiled (transpiled) to JavaScript before it can run in the browser or Node.js.
Key Benefits: - Early error detection. - Stronger tooling support like autocompletion and refactoring. - Type safety improves code reliability.
2. Setting up TypeScript (3 minutes)¶
Option 1: Try TypeScript in your browser: - Use TypeScript Playground for instant experimentation without any setup.
Option 2: Install TypeScript locally:
1. Install Node.js and npm if you don’t have them.
2. Run the following command to install TypeScript globally:
bash
npm install -g typescript
3. Create a new .ts
file (e.g., app.ts
).
4. Compile your TypeScript code to JavaScript by running:
bash
tsc app.ts
5. You can also watch files and recompile automatically with:
bash
tsc --watch
3. Basic Types in TypeScript (4 minutes)¶
Declaring Variables with Types¶
- TypeScript allows you to declare the type of a variable.
let age: number = 30;
let name: string = "John";
let isActive: boolean = true;
Arrays and Objects¶
- You can also define types for arrays and objects.
let numbers: number[] = [1, 2, 3];
let user: { name: string; age: number } = { name: "John", age: 30 };
Union Types¶
- Union types allow variables to hold more than one type.
let mixed: string | number;
mixed = "Hello";
mixed = 42;
4. Functions in TypeScript (4 minutes)¶
Function Parameter Types¶
- You can specify types for function parameters and the return value.
function add(a: number, b: number): number {
return a + b;
}
- TypeScript ensures that the parameters passed to
add
are both numbers.
Optional Parameters¶
- You can make function parameters optional by using the
?
symbol.
function greet(name: string, age?: number): string {
return `Hello ${name}, you are ${age ? age : "ageless"}!`;
}
Default Parameters¶
- You can also assign default values to parameters.
function multiply(a: number, b: number = 2): number {
return a * b;
}
5. Interfaces and Types (3 minutes)¶
Interfaces¶
- Interfaces define the structure of an object.
interface Person {
name: string;
age: number;
greet(): string;
}
const person: Person = {
name: "Alice",
age: 25,
greet() {
return "Hello!";
},
};
- TypeScript ensures that
person
adheres to thePerson
interface structure.
Type Aliases¶
- You can also define custom types with type aliases.
type ID = string | number;
let userId: ID = 101; // Can be either a string or number
6. Classes in TypeScript (4 minutes)¶
TypeScript enhances JavaScript classes by adding type safety and features like access modifiers (public
, private
, protected
).
class Car {
private brand: string;
constructor(brand: string) {
this.brand = brand;
}
public getBrand(): string {
return this.brand;
}
}
const car = new Car("Toyota");
console.log(car.getBrand()); // Outputs: Toyota
- The
private
keyword restricts access to thebrand
property, so it can't be accessed outside the class.
7. TypeScript Generics (3 minutes)¶
Generics allow you to create reusable components with flexible types.
function identity<T>(value: T): T {
return value;
}
console.log(identity<number>(5)); // Outputs: 5
console.log(identity<string>("Hello")); // Outputs: Hello
- In this example,
T
is a placeholder for a type that is specified when calling the function.
8. Enums in TypeScript (2 minutes)¶
Enums allow you to define a set of named constants.
enum Direction {
Up = 1,
Down,
Left,
Right,
}
let dir: Direction = Direction.Up;
console.log(dir); // Outputs: 1
9. Working with Modules (2 minutes)¶
You can use TypeScript’s module system to organize your code.
Exporting:
export function greetUser(name: string): void {
console.log(`Hello, ${name}`);
}
Importing:
import { greetUser } from "./module";
greetUser("Alice");
10. Final Tips (1 minute)¶
- TypeScript Compiler Options: You can configure TypeScript using a
tsconfig.json
file. This allows you to set strict type-checking rules or specify output directories for compiled JavaScript. - TypeScript Documentation: Refer to the official docs for advanced features and further learning.
Now you’ve got a basic understanding of TypeScript and its core features! Use this to gradually move from JavaScript to TypeScript for better, safer code.
Backquotes¶
(also known as backticks) `
are different from single ('
) or double ("
) quotes. In JavaScript and TypeScript, backticks are used to create template literals (also called template strings), which offer several features not available with single or double quotes.
Key Features of Backticks:¶
-
Multi-line Strings: You can write strings that span multiple lines without needing to concatenate strings or use special characters like
\n
.js const multiLineString = `This is a string that spans multiple lines.`;
-
String Interpolation: You can embed expressions inside a string using
${}
.js const name = 'John'; const greeting = `Hello, ${name}!`; // Outputs: "Hello, John!"
-
Embedding Expressions: You can embed any JavaScript expression inside
${}
, and it will be evaluated.js const a = 10; const b = 20; const result = `The sum of a and b is ${a + b}`; // Outputs: "The sum of a and b is 30"
In contrast, single and double quotes are used for plain strings that don’t allow multi-line text or expression embedding.
Example:¶
// Using single quotes
const singleQuoteString = 'Hello, John!';
// Using double quotes
const doubleQuoteString = "Hello, John!";
// Using backticks (template literals)
const name = 'John';
const templateLiteral = `Hello, ${name}!`; // Embeds the variable name
So backticks are more powerful and flexible, especially when you need to work with dynamic content or multi-line strings.