DEV Community

Frontend Nomad
Frontend Nomad

Posted on

Advanced TypeScript Tricks

Mastering TypeScript means making the most of its type system. Here are three advanced tips you can use daily.

Conditional Types

type IsString<T> = T extends string ? true : false;
type A = IsString<'abc'>; // true
type B = IsString<123>;   // false
Enter fullscreen mode Exit fullscreen mode

This type adapts depending on the input!

Utility Types

Use built-in utility types:

type User = { id: number; name: string; };
type PartialUser = Partial<User>; // All properties become optional
Enter fullscreen mode Exit fullscreen mode

Mapped Types

Create new types based on existing ones:

type User = { id: number; name: string; };
type AllStrings = { [K in keyof User]: string };
// { id: string; name: string; }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Playing with these tools helps you write more robust and maintainable TypeScript code.

Top comments (0)