TypeScript Cheatsheet
TypeScript Cheatsheet¶
Overview¶
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It offers optional static typing, classes, and interfaces. TypeScript is designed for development of large applications and transcompiles to JavaScript.
Key Features¶
- Static Typing: Catch errors at compile time instead of at runtime.
- Interfaces: Define contracts for your code.
- Classes: Use object-oriented programming features like classes, inheritance, and access modifiers.
- Generics: Create reusable components that can work with a variety of types.
Getting Started¶
Install TypeScript:
Compile a TypeScript file:
Basic Types¶
boolean:trueorfalse.number: All numbers are floating point types.string: Textual data.array: An array of values of a specific type.tuple: An array with a fixed number of elements of different types.enum: A way of giving more friendly names to sets of numeric values.any: A dynamic type that can be anything.void: The absence of any type at all.null`` andundefined**: Subtypes of all other types.never: Represents the type of values that never occur.
Interfaces¶
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "Jane", lastName: "User" };
document.body.textContent = greeter(user);
Classes¶
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");