DEV Community

Cover image for Tips and Tricks That Every Typescript Developer Should Know
Sonu Sharma 💙
Sonu Sharma 💙

Posted on

Tips and Tricks That Every Typescript Developer Should Know

Tips and Tricks for TypeScript Developers

TypeScript has become the go-to language for building scalable web applications in recent years. It is a superset of JavaScript that offers static typing and a host of other features, making it easier to write code that is less error-prone and more maintainable.
If you are a TypeScript developer or looking to become one, here are some tips and tricks you should know to enhance your development.
Image

1. Embrace the Type System

one of the primary advantages of typescript is its type system, which allows you to catch potential bugs at compile-time. Ensure that you take advantage of the type system in TypeScript by thoroughly annotating your types.

Example:

function add(a: number, b: number): number {
   return a + b;
}
Enter fullscreen mode Exit fullscreen mode

2. Use Generics

Generic types allow you to write reusable code that can adapt to different types easily. This feature can save you time and lines of code by allowing you to define functions and classes that work with multiple data types.

Example:

interface IProduct<T> {
  id: string;
  name: string;
  price: T;
}


const product: IProduct<number> = {
    id: '1234',
    name: 'Product Name',
    price: 500,
};

Enter fullscreen mode Exit fullscreen mode

3. Take Advantage of Enums

An enum is a type of data that allows a variable to have one of several predefined values. They help you keep your code maintainable and easy to understand by defining a set of related values.

Example:

enum Direction {
  LEFT,
  RIGHT,
  UP,
  DOWN,
}

let direction = Direction.LEFT;
Enter fullscreen mode Exit fullscreen mode

4. Use Intersection Types

Intersection types allow you to merge multiple types into a single type.

Example:

type X = {
  x: string;
};

type Y = {
  y: string;
};

type XY = X & Y;

const xy: XY = { x: 'hello', y: 'world' };
Enter fullscreen mode Exit fullscreen mode

5. Use Optional Chaining

Optional chaining allows you to access nested properties or methods without having to check if each level exists.
Example:

const name = user?.firstName ?? 'Unknown';
Enter fullscreen mode Exit fullscreen mode

6. Use Nullish Coalescing

Nullish coalescing allows you to provide a default value when a value is null or undefined.
Example:

const name = user.firstName ?? 'Unknown';
Enter fullscreen mode Exit fullscreen mode

7. Use Read-Only Properties

Read-only properties ensure that a property value cannot be changed after it is instantiated, including in constructors.
Example:

class Person {
  readonly name: string;

  constructor(name: string) {
    this.name = name;
  }
}
Enter fullscreen mode Exit fullscreen mode

8. Use Destructuring

Destructuring allows you to extract values from objects and arrays into separate variables.
Example:

const { firstName, lastName } = user;
Enter fullscreen mode Exit fullscreen mode

9. Use Type Aliases

Type aliases allow you to create a name for a type that is used multiple times.
Example:

type User = {
  firstName: string;
  lastName: string;
};

function greet(user: User) {
  console.log(`Hello, ${user.firstName} ${user.lastName}`);
}
Enter fullscreen mode Exit fullscreen mode

10. Use Type Assertions

Type assertions allow you to tell TypeScript to treat a value as a specific type in specific situations.
Example:

const x: unknown = 'hello world';
const y = (x as string).toUpperCase();
Enter fullscreen mode Exit fullscreen mode

11. Use the never Type

The never type represents a value that will never occur.
Example:

function fail(message: string): never {
  throw new Error(message);
}
Enter fullscreen mode Exit fullscreen mode

12. Use the Spread Operator

The spread operator allows you to create a new array or object by merging existing ones.
Example:

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

13. Use Union Types

Union types allow you to define a type that can have one of several types.
Example:

type Status = 'success' | 'failure';

function getStatus(status: Status) {
  console.log(`status is ${status}`);
}
Enter fullscreen mode Exit fullscreen mode

14. Use Enums for String Literals

Enums can also be used to define string literals.
Example:

enum Status {
  Success = 'Success',
  Failure = 'Failure',
}

function getStatus(status: Status) {
  console.log(`status is ${status}`);
}

Enter fullscreen mode Exit fullscreen mode

15. Use keyof to get Keys of Objects

The keyof keyword allows you to get the keys of an object.
Example:

type User = {
  firstName: string;
  lastName: string;
};

const keys: Array<keyof User> = ['firstName', 'lastName'];
Enter fullscreen mode Exit fullscreen mode

16. Use typeof to get the Type of a Variable

The typeof keyword allows you to get the type of a variable at runtime.
Example:

const x = 10;
const y: typeof x = 20;
Enter fullscreen mode Exit fullscreen mode

17. Use in Operator For Checking Properties of Objects

The in operator allows you to check if a property exists on an object.
Example:

type User = {
  firstName?: string;
  lastName?: string;
};

function greet(user: User) {
  if ('firstName' in user) {
    console.log(`Hello, ${user.firstName}`);
  } else {
    console.log('Hello');
  }
}
Enter fullscreen mode Exit fullscreen mode

18. Use String Interpolation

String interpolation allows you to embed expressions in string literals.
Example:

const firstName = 'John';
const lastName = 'Doe';
console.log(`Hello, ${firstName} ${lastName}`);
Enter fullscreen mode Exit fullscreen mode

19. Use typeof for Type Guards

Using typeof in conjunction with if-else statements can serve as an alternative to type guard syntax.
Example:

function example(foo: string | number): void {
  if (typeof foo === 'string') {
    console.log('string');
  } else {
    console.log('number');
  }
}
Enter fullscreen mode Exit fullscreen mode

20. Use export * as to Re-Export Modules

The export * as syntax allows you to re-export all named exports of a module under a separate namespace.
Example:

// module1.ts
export const foo = 1;
export const bar = 2;

// module2.ts
export * as module1 from './module1';
Enter fullscreen mode Exit fullscreen mode

21. Use Tuples for Fixed-Length Arrays

Tuples allow you to define an array with a fixed number of elements, with different types.

Example:

const tuple: [number, string] = [1, 'hello'];
Enter fullscreen mode Exit fullscreen mode

22. Utilize TSLint

TSlint is a tool that provides linters for TypeScript, statically analyzing the code and providing guidelines on how to improve the quality of the codebase, resulting in cleaner and quality code.

Example:

 npm install -g tslint

Enter fullscreen mode Exit fullscreen mode

Conclusion

The techniques discussed in this article are a good starting point for becoming a Typescript developer, knowing the basics will save one a lot of shoot-my-foot moments during the code review and debugging phase.
These are just a few tips and tricks that can greatly improve your development with TypeScript. Other options include applying object-oriented approaches and utilizing external libraries correctly. By applying these techniques and more, you can employ the full capabilities of TypeScript, building robust, scalable applications.

Top comments (0)