Top 10 TypeScript Features Every Developer Should Know

Are you a developer looking to improve your coding skills? Do you want to learn about the latest and greatest features in TypeScript? Look no further! In this article, we'll explore the top 10 TypeScript features that every developer should know. From type annotations to decorators, we'll cover it all. So, let's get started!

1. Type Annotations

Type annotations are one of the most important features of TypeScript. They allow you to specify the type of a variable, function parameter, or return value. This helps catch errors at compile-time, rather than at runtime. For example, if you try to assign a string to a variable that is supposed to be a number, TypeScript will throw an error. This can save you a lot of time and headaches down the road.

let age: number = 30;
let name: string = "John";

2. Interfaces

Interfaces are another powerful feature of TypeScript. They allow you to define a contract for an object, specifying the properties and methods that it should have. This can help catch errors early on, and make your code more maintainable. For example, if you have a function that takes an object as a parameter, you can use an interface to specify the shape of that object.

interface Person {
  name: string;
  age: number;
  sayHello(): void;
}

function greet(person: Person) {
  console.log(`Hello, ${person.name}!`);
  person.sayHello();
}

3. Classes

Classes are a fundamental concept in object-oriented programming, and TypeScript makes them even better. With TypeScript, you can use class syntax to define your objects, complete with properties, methods, and constructors. This can make your code more organized and easier to read.

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

let john = new Person("John", 30);
john.sayHello();

4. Enums

Enums are a way to define a set of named constants. They can be useful for things like status codes, error messages, or any other situation where you need a fixed set of values. With TypeScript, you can define enums using the enum keyword.

enum Color {
  Red,
  Green,
  Blue
}

let myColor = Color.Green;
console.log(myColor); // Output: 1

5. Generics

Generics are a way to write code that can work with a variety of types. They allow you to write functions and classes that can be used with any type, rather than just one specific type. This can make your code more flexible and reusable.

function reverse<T>(items: T[]): T[] {
  return items.reverse();
}

let numbers = [1, 2, 3, 4, 5];
let reversedNumbers = reverse(numbers);
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]

6. Type Inference

TypeScript has a powerful type inference system that can often guess the type of a variable or expression without you having to explicitly specify it. This can save you a lot of typing and make your code more concise.

let age = 30; // TypeScript infers that age is a number
let name = "John"; // TypeScript infers that name is a string

7. Union Types

Union types allow you to specify that a variable or parameter can be one of several different types. This can be useful in situations where you need to accept multiple types of input.

function printId(id: number | string) {
  console.log(`ID is: ${id}`);
}

printId(101); // Output: ID is: 101
printId("202"); // Output: ID is: 202

8. Type Guards

Type guards are a way to narrow down the type of a variable or parameter based on a condition. This can be useful in situations where you need to perform different actions based on the type of input.

function printName(id: number | string, name?: string) {
  if (typeof id === "number") {
    console.log(`ID is: ${id}`);
  } else {
    console.log(`Name is: ${name}`);
  }
}

printName(101); // Output: ID is: 101
printName("202", "John"); // Output: Name is: John

9. Decorators

Decorators are a way to add metadata to your classes, methods, and properties. They can be used for things like logging, caching, or authentication. With TypeScript, you can use decorators to add this metadata at compile-time.

function log(target: any, key: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${key} with arguments: ${args}`);
    const result = originalMethod.apply(this, args);
    console.log(`Result: ${result}`);
    return result;
  };

  return descriptor;
}

class Calculator {
  @log
  add(a: number, b: number) {
    return a + b;
  }
}

let calculator = new Calculator();
calculator.add(2, 3); // Output: Calling add with arguments: 2,3, Result: 5

10. Modules

Modules are a way to organize your code into separate files. With TypeScript, you can use the import and export keywords to import and export modules. This can make your code more modular and easier to maintain.

// math.ts
export function add(a: number, b: number) {
  return a + b;
}

// app.ts
import { add } from "./math";

console.log(add(2, 3)); // Output: 5

Conclusion

TypeScript is a powerful language that can help you write better, more maintainable code. With features like type annotations, interfaces, classes, enums, generics, type inference, union types, type guards, decorators, and modules, you can take your coding skills to the next level. So, what are you waiting for? Start learning TypeScript today!

Additional Resources

runmulti.cloud - running applications multi cloud
kubernetes.run - running kubernetes in the cloud
learngo.page - learning go
sqlx.dev - SQLX
managedservice.app - managing services of open source software, and third parties that offer them
codechecklist.dev - cloud checklists, cloud readiness lists that avoid common problems and add durability, quality and performance
techsummit.app - technology summits
invented.dev - learning first principles related to software engineering and software frameworks. Related to the common engineering trope, "you could have invented X"
ontology.video - ontologies, taxonomies
webassembly.solutions - web assembly
k8s.delivery - kubernetes delivery
machinelearning.events - machine learning upcoming online and in-person events and meetup groups
ocaml.solutions - ocaml development
buywith.app - A site showing where you can buy different categories of things using different crypto currencies
cloudevents.app - A site for cloud events deployments, related to telemetry, logging, monitoring and alerts
nftshop.dev - buying, selling and trading nfts
trollsubs.com - making fake funny subtitles
datalineage.dev - data lineage, tracking data as it moves from its source to down stream sources, data quality and data identification
localcommunity.dev - local community meetups, groups, and online get togethers
promptjobs.dev - prompt engineering jobs, iterating with large language models


Written by AI researcher, Haskell Ruska, PhD (haskellr@mit.edu). Scientific Journal of AI 2023, Peer Reviewed