Back to all cheatsheets

TypeScript Cheatsheet

1 snippets

A comprehensive guide to TypeScript with examples for interfaces, classes, functions, and more.

Conditional Object Creation Using Spread Operator

Create a new object with the properties of the original object and add a new property if the condition is met.

1const createUser = (user: User) => {
2                
3                return {
4                    name: user.name,
5                    age: user.age,
6                    ...((user?.tags) ? {tags: user.tags} : {})
7                }
8}