Five quickfire TypeScript tips

Author image

Joe

Director and Lead Software Engineer

Author image

Here are five quickfire TypeScript tips:

1. Use unknown instead of any: The unknown type is a safer alternative to any. While any allows you to do anything without type checking, unknown forces you to perform some type of checking before you can use the value.

let value: unknown;
value = "Hello"; // OK
value = 123; // OK
console.log(value.length); // Error: Object is of type 'unknown'.

2. Type assertions: If you're sure about the type of a value, you can use a type assertion to tell TypeScript. This can be useful when you're working with values of type any or unknown.

let value: unknown = "Hello world!";
let length: number = (value as string).length; // OK

3. Nullish coalescing operator (??): This operator returns the first operand if it's not null or undefined. Otherwise, it returns the second operand. This can be useful when you want to provide a default value for a variable.

let value = null;
let defaultValue = "Default value";
console.log(value ?? defaultValue); // "Default value"

4. Optional chaining (?.): This operator allows you to access the properties of an object even if the object is null or undefined, without throwing an error.

let user = null;
console.log(user?.name); // undefined

5. Mapped types: TypeScript allows you to create new types based on old ones using mapped types. For example, you can create a read-only version of an existing type using Readonly.

type Point = { x: number; y: number };
type ReadonlyPoint = Readonly<Point>;
let p: ReadonlyPoint = { x: 1, y: 2 };
p.x = 3; // Error: Cannot assign to 'x' because it is a read-only property.

Remember, TypeScript is a powerful tool that can help you write safer and more reliable code. These tips are just the tip of the iceberg!