teach me typescript
- User
teach me typescript
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
teach me typescript
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
TypeScript is a powerful, statically-typed superset of JavaScript that adds features like type annotations, interfaces, enums, and more to help developers write safer and more maintainable code. It compiles down to plain JavaScript, so it can run anywhere JavaScript runs (browsers, Node.js, etc.).
In this guide, I'll teach you TypeScript step by step, starting with the basics and moving to more advanced concepts. Let's get started!
tsc).TypeScript requires Node.js. Download and install it from nodejs.org.
Run the following command to install TypeScript globally:
npm install -g typescript
Create a file with a .ts extension, e.g., index.ts.
Run the TypeScript compiler (tsc) to convert your .ts file to .js:
tsc index.ts
This will generate an index.js file that you can run with Node.js:
node index.js
To set up a TypeScript project with a configuration file, run:
tsc --init
This creates a tsconfig.json file, which allows you to configure the TypeScript compiler (e.g., target JavaScript version, strict mode, etc.).
TypeScript introduces static types to JavaScript. Here are the basic types:
// Boolean
let isDone: boolean = false;
// Number
let age: number = 25;
// String
let name: string = "Alice";
// Array
let numbers: number[] = [1, 2, 3];
// Alternative syntax for arrays
let strings: Array<string> = ["a", "b", "c"];
// Tuple (fixed-length array with specific types)
let tuple: [string, number] = ["Alice", 25];
// Enum
enum Color {
Red,
Green,
Blue,
}
let color: Color = Color.Green; // 1
// Any (avoid using this when possible, as it disables type checking)
let anything: any = 42;
anything = "hello";
// Void (for functions that return nothing)
function logMessage(): void {
console.log("Hello, TypeScript!");
}
// Null and Undefined
let n: null = null;
let u: undefined = undefined;
// Never (for functions that never return, e.g., throw an error)
function throwError(message: string): never {
throw new Error(message);
}
TypeScript can often infer types without explicit annotations:
let inferredString = "hello"; // TypeScript infers `string`
inferredString = 42; // Error: Type 'number' is not assignable to type 'string'
A variable can have more than one type:
let value: string | number;
value = "hello"; // OK
value = 42; // OK
value = true; // Error
You can tell TypeScript that you know the type of a value:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
// Alternative syntax
let strLengthAlt: number = (<string>someValue).length;
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add("2", "3")); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
Use ? to make parameters optional:
function greet(name: string, greeting?: string): string {
return `${greeting || "Hello"}, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"
console.log(greet("Bob", "Hi")); // "Hi, Bob!"
function greetWithDefault(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}
console.log(greetWithDefault("Alice")); // "Hello, Alice!"
console.log(greetWithDefault("Bob", "Hi")); // "Hi, Bob!"
You can define the type of a function:
let myAdd: (x: number, y: number) => number;
myAdd = function (a: number, b: number): number {
return a + b;
};
Interfaces define the shape of an object:
interface User {
id: number;
name: string;
email?: string; // Optional property
}
function printUser(user: User): void {
console.log(`ID: ${user.id}, Name: ${user.name}`);
}
const user: User = { id: 1, name: "Alice" };
printUser(user); // ID: 1, Name: Alice
interface Admin extends User {
isAdmin: boolean;
}
const admin: Admin = { id: 2, name: "Bob", isAdmin: true };
Type aliases are similar to interfaces but can represent more than just objects:
type Point = {
x: number;
y: number;
};
const point: Point = { x: 10, y: 20 };
interface for object shapes and when you want to extend or implement.type for unions, intersections, or other complex type definitions.TypeScript enhances JavaScript classes with type annotations, access modifiers, and more.
class Person {
private name: string; // Only accessible within the class
public age: number; // Accessible everywhere
protected email: string; // Accessible within the class and subclasses
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
public getName(): string {
return this.name;
}
}
const person = new Person("Alice", 25, "alice@example.com");
console.log(person.age); // 25
console.log(person.getName()); // "Alice"
// console.log(person.name); // Error: Property 'name' is private
class Employee extends Person {
constructor(name: string, age: number, email: string, private role: string) {
super(name, age, email);
}
public getRole(): string {
return this.role;
}
}
const employee = new Employee("Bob", 30, "bob@example.com", "Developer");
console.log(employee.getName()); // "Bob"
console.log(employee.getRole()); // "Developer"
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log("Moving...");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Woof!");
}
}
const dog = new Dog();
dog.makeSound(); // "Woof!"
dog.move(); // "Moving..."
interface Printable {
print(): void;
}
class Document implements Printable {
print(): void {
console.log("Printing document...");
}
}
const doc = new Document();
doc.print(); // "Printing document..."
Generics allow you to create reusable components that work with any type.
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("Hello")); // "Hello"
console.log(identity<number>(42)); // 42
You can restrict the types that can be used with generics:
interface Lengthy {
length: number;
}
function getLength<T extends Lengthy>(item: T): number {
return item.length;
}
console.log(getLength("hello")); // 5
console.log(getLength([1, 2, 3])); // 3
// console.log(getLength(42)); // Error: Argument of type 'number' is not assignable to parameter of type 'Lengthy'
class Box<T> {
private content: T;
constructor(value: T) {
this.content = value;
}
getContent(): T {
return this.content;
}
}
const stringBox = new Box<string>("Hello");
console.log(stringBox.getContent()); // "Hello"
const numberBox = new Box<number>(42);
console.log(numberBox.getContent()); // 42
TypeScript supports ES6 module syntax (import/export).
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.14;
// main.ts
import { add, PI } from "./math";
console.log(add(2, 3)); // 5
console.log(PI); // 3.14
// logger.ts
export default class Logger {
log(message: string): void {
console.log(message);
}
}
// main.ts
import Logger from "./logger";
const logger = new Logger();
logger.log("Hello, TypeScript!");
Combine multiple types into one:
type A = { a: number };
type B = { b: string };
type C = A & B;
const obj: C = { a: 1, b: "hello" };
Narrow down the type of a value within a conditional block:
function isString(value: string | number): value is string {
return typeof value === "string";
}
function processValue(value: string | number): void {
if (isString(value)) {
console.log(value.toUpperCase()); // TypeScript knows `value` is a string
} else {
console.log(value.toFixed(2)); // TypeScript knows `value` is a number
}
}
Restrict a value to specific literals:
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // OK
// move("diagonal"); // Error
Create new types based on existing ones:
type Optional<T> = {
[P in keyof T]?: T[P];
};
interface User {
id: number;
name: string;
}
const optionalUser: Optional<User> = { id: 1 }; // `name` is optional
Define types based on conditions:
type IsString<T> = T extends string ? "yes" : "no";
type Test1 = IsString<string>; // "yes"
type Test2 = IsString<number>; // "no"
Decorators are a way to add metadata or modify classes, methods, properties, or parameters. They are commonly used in frameworks like Angular.
function logClass(target: Function) {
console.log(`Class ${target.name} is being created`);
}
@logClass
class MyClass {
constructor() {
console.log("Instance created");
}
}
const instance = new MyClass();
// Output:
// Class MyClass is being created
// Instance created
To use decorators, enable the experimentalDecorators option in tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true
}
}
TypeScript is widely used with frameworks like:
.tsx files for React components with TypeScript.npm install --save-dev @types/react @types/react-dom
import React from "react";
interface Props {
name: string;
}
const Greeting: React.FC<Props> = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
export default Greeting;
npm install --save-dev @types/node
import express, { Request, Response } from "express";
const app = express();
app.get("/", (req: Request, res: Response) => {
res.send("Hello, TypeScript!");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
"strict": true in tsconfig.json to catch more errors.any: Use specific types whenever possible.tsconfig.json Configured Properly: Set options like target, module, and outDir appropriately for your project.If you have any specific questions or want to dive deeper into a particular topic, let me know! Happy coding! 🚀