TypeScript Basics
(Updated on )
TypeScript Basics
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. In this guide, we’ll explore the fundamental concepts of TypeScript.
What is TypeScript?
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing and class-based object-oriented programming to JavaScript.
Basic Types
Primitive Types
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];
Enum
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
Any and Unknown
let notSure: any = 4;
notSure = "maybe a string instead";
let value: unknown = 4;
if (typeof value === "number") {
let numberValue: number = value;
}
Interfaces
interface User {
name: string;
age: number;
email?: string; // Optional property
readonly id: number; // Read-only property
}
const user: User = {
name: "John",
age: 30,
id: 1
};
Functions
function add(x: number, y: number): number {
return x + y;
}
const multiply = (x: number, y: number): number => x * y;
function processUser(user: User): void {
console.log(user.name);
}
Classes
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
Generics
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString");
let output2 = identity<number>(42);
Type Assertions
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;
Best Practices
- Use strict type checking
- Avoid using
anytype - Use interfaces for object shapes
- Leverage type inference
- Use union types for flexibility
Next Steps
- Learn about Advanced TypeScript
- Explore TypeScript with React
- Master TypeScript Design Patterns
Happy coding!