Tillitsdone
down Scroll to discover

Advanced TypeScript Tricks to Improve Code

Discover powerful TypeScript features including discriminated unions, template literal types, conditional types with infer, mapped types, and const assertions to build more maintainable applications.
thumbnail

Advanced TypeScript Tricks to Improve Your Codebase

Abstract geometric pattern representing code organization featuring interlocking hexagons and flowing lines in bright blue and off-white colors shot from top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Ever felt like you’re just scratching the surface of TypeScript? Let’s dive deep into some advanced techniques that will take your codebase to the next level. These aren’t just your everyday tips – they’re battle-tested strategies I’ve gathered from years of working with TypeScript in production environments.

1. Leveraging Discriminated Unions

One of TypeScript’s most powerful features is its ability to handle complex type relationships. Discriminated unions are game-changers when dealing with related but distinct types.

type Success = {
status: 'success';
data: string[];
};
type Error = {
status: 'error';
message: string;
};
type Response = Success | Error;
function handleResponse(response: Response) {
if (response.status === 'success') {
// TypeScript knows response.data exists here
response.data.map(item => console.log(item));
} else {
// TypeScript knows response.message exists here
console.error(response.message);
}
}

Modern minimalist architecture with clean lines and geometric shapes warm butterscotch yellow tones with contrasting shadows photographed from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

2. Template Literal Types

Template literal types are like string templates but at the type level. They’re incredibly useful for creating precise string-based types.

type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type APIEndpoint = '/users' | '/posts' | '/comments';
type ValidRequest = `${HTTPMethod} ${APIEndpoint}`;
// Type-safe API requests
function makeRequest(request: ValidRequest) {
// Only valid combinations are allowed
}
makeRequest('GET /users'); // Valid
makeRequest('POST /invalid'); // Error!

3. Conditional Types and infer

The infer keyword, combined with conditional types, lets us extract types from other types. It’s like pattern matching for types:

type UnwrapPromise\<T\> = T extends Promise<infer U> ? U : T;
// Example usage
type PromiseString = Promise<string>;
type ExtractedString = UnwrapPromise<PromiseString>; // string

Flowing abstract waves and curves in bright neon green and black creating a dynamic composition captured from a diagonal perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

4. Mapped Types with Key Remapping

Take your mapped types to the next level with key remapping. This feature lets you transform both the keys and values of your types:

type Getters\<T\> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
// {
// getName: () => string;
// getAge: () => number;
// }

5. Using const Assertions

The as const assertion can make your objects immutable and their types more specific:

const config = {
endpoint: 'api.example.com',
version: 'v1',
features: ['auth', 'messages'] as const
} as const;
// Now config.features is readonly ['auth', 'messages']
// Instead of string[]

Conclusion

These TypeScript features might seem advanced at first, but they’re invaluable tools for building more maintainable and type-safe applications. Start incorporating them gradually into your codebase, and you’ll see the benefits of stronger type checking and better developer experience.

Elegant white flower arrangement with soft natural lighting against a clean backdrop in bright Amethyst color tones photographed from a slightly elevated front view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/code-outline.svg Typescript Blogs
Superset of JavaScript adding static types for improved code quality and maintainability.
icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.