Typescript is a static-typed language created by Microsoft in 2012. It is a superset of JavaScript. So, Javascript code is valid Typescript code. But Typescript code is not valid Javascript code. Typescript does not run natively in the browser. It uses a compiler that transpiles Typescript code into Native Javascript code for the web browser. In this blog post, we are going to cover the basics of TypeScript. This cheat sheet includes Typescript features(i.e. types, interfaces etc.)
Variables
Typescript is a strongly typed language. So, typed annotations are optional. You can declare variables in Typescript just like in JavaScript by using var
, let
and const
.
let variableOne = 'This feels familiar...'
// Implicit - type inferred as 'string' by default due to the assignment
let variableTwo: string = "Hello, Typescript"
// Explicit - type explicitly inferred as 'string'
Basic Types
These are the basic types in Typescript. These include numbers, strings, enums and many more.
// Primitive Types
let num: number = 42;
let str: string = "Hello, TypeScript";
let bool: boolean = true;
// Arrays
let numArray: number[] = [1, 2, 3];
let strArray: string[] = ["apple", "banana", "cherry"];
// Tuples
let tuple: [string, number] = ["John", 30];
// Enums
enum Color {
Red,
Green,
Blue
}
let color: Color = Color.Red;
// Any (Use with caution)
let anyValue: any = "This can be of any type";
Functions
In TypeScript, functions play a crucial role in building reusable and structured code. Functions in TypeScript can have strongly typed parameters and return values, offering enhanced type safety and code predictability. You can define function signatures using explicit type annotations or let TypeScript infer types automatically. TypeScript supports features like optional parameters, default parameter values, rest parameters, and function overloading, making it versatile for various programming needs. Additionally, TypeScript allows you to define arrow functions, which simplify syntax and provide a concise way to create functions. Functions are a fundamental building block in TypeScript, enabling you to encapsulate logic, promote code reusability, and maintain type consistency throughout your applications.
function add(x: number, y: number): number {
return x + y;
}
// Optional parameters
function greet(name: string, age?: number): void {
console.log(`Hello, ${name}${age ? `, Age: ${age}` : ""}`);
}
// Default parameters
function say(message: string = "Hello"): void {
console.log(message);
}
Interfaces and Objects
In TypeScript, interfaces are a way to define the shape or structure that objects should adhere to. They provide a blueprint for defining the properties and methods that an object should have. Interfaces are used to ensure consistency and type safety in your code. When you create an object that implements an interface, it must include all the properties and methods specified by that interface. This helps catch potential errors during development and makes your code more maintainable and predictable. Interfaces are a fundamental concept in TypeScript, enabling you to define contracts for object shapes and promoting code clarity and reliability.
// Interfaces
interface Person {
name: string;
age: number;
}
// Objects
let person: Person = {
name: "Alice",
age: 25,
};
// Type Aliases
type Point = { x: number; y: number };
let point: Point = { x: 10, y: 20 };
Classes
In TypeScript, classes provide a blueprint for creating objects with defined properties and methods. They are an integral part of object-oriented programming, allowing you to encapsulate data and behaviour within a single unit. TypeScript classes support inheritance, access modifiers (public, private, protected), constructors for initializing objects, and interfaces for defining the structure a class should adhere to. By using classes, you can create reusable and organized code, promoting modularity and maintainability in your TypeScript applications.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a sound`);
}
}
let dog = new Animal("Dog");
dog.speak();
Generics
Generics in TypeScript allow you to write reusable and flexible code by creating functions, classes, and interfaces that can work with different data types while preserving type safety. With generics, you can write functions or classes that can adapt to various input types, making your code more versatile and reducing the need for repetitive code. TypeScript's type inference system ensures that the correct types are used, enhancing code reliability and maintainability. Generics are especially useful when working with data structures, algorithms, and libraries where you want to provide type-safe and flexible solutions for different scenarios.
function identity<T>(value: T): T {
return value;
}
let result = identity<string>("Hello, Generics");
Conclusion
This covers the fundamentals of Typescript and if you want to learn more about it. Then refer to TypeScript Documentation.
Top comments (0)