For Javascript Developers
Here are some example topics to explore for learning TypeScript:
Basic Types
// In JavaScript, you write:
let name = "John";
let age = 25;
let isStudent = true;
// In TypeScript, you can add type annotations:
let name: string = "John";
let age: number = 25;
let isStudent: boolean = true;
// TypeScript can also infer types automatically:
let inferredString = "John"; // TypeScript knows this is a string
let inferredNumber = 25; // TypeScript knows this is a number
Arrays and Objects
// Arrays
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["John", "Jane"];
// Alternative array syntax
let numbers2: Array<number> = [1, 2, 3, 4, 5];
// Objects
// Define an object type
type Person = {
name: string;
age: number;
isStudent?: boolean; // ? means optional property
};
// Use the type
let student: Person = {
name: "John",
age: 25,
isStudent: true
};
Functions
// Basic function
function add(a: number, b: number): number {
return a + b;
}
// Arrow function
const multiply = (a: number, b: number): number => a * b;
// Function with optional parameter
function greet(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
}
return `Hello, ${name}!`;
}
// Function with default parameter
function greetWithDefault(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
Interfaces (Similar to types but for objects)
interface User {
name: string;
age: number;
email: string;
sayHello(): string;
}
// Implementing an interface
class Student implements User {
constructor(
public name: string,
public age: number,
public email: string
) {}
sayHello() {
return `Hello, I'm ${this.name}`;
}
}
React with TypeScript
// Defining props interface
interface ButtonProps {
text: string;
onClick: () => void;
color?: string;
}
// Function component with TypeScript
const Button: React.FC<ButtonProps> = ({ text, onClick, color = 'blue' }) => {
return (
<button
onClick={onClick}
style={{ backgroundColor: color }}
>
{text}
</button>
);
};
// Using useState with TypeScript
const Counter: React.FC = () => {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Common TypeScript Utility Types
// Partial - Makes all properties optional
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
// Pick - Select specific properties
type TodoPreview = Pick<Todo, 'title'>;
// Omit - Remove specific properties
type TodoWithoutDescription = Omit<Todo, 'description'>;
// Readonly - Make all properties readonly
type ReadonlyTodo = Readonly<Todo>;
Union Types and Type Narrowing
// Union types
type Status = 'loading' | 'success' | 'error';
function handleStatus(status: Status) {
switch (status) {
case 'loading':
return 'Loading...';
case 'success':
return 'Data loaded!';
case 'error':
return 'Error loading data';
}
}
// Type narrowing with typeof
function processValue(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase(); // TypeScript knows it's a string
}
return value * 2; // TypeScript knows it's a number
}
Generic Types
// Generic function
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}
// Usage
const numbers = firstElement([1, 2, 3]); // Type: number
const strings = firstElement(['a', 'b', 'c']); // Type: string
// Generic interface
interface Box<T> {
value: T;
}
const stringBox: Box<string> = { value: 'Hello' };
const numberBox: Box<number> = { value: 42 };
Try out these examples yourself to get comfortable with using TypeScript in your daily work.
Join Akshay on Peerlist!
Join amazing folks like Akshay and thousands of other people in tech.
Create ProfileJoin with Akshay’s personal invite link.
0
8
0