ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Ts Utility Types in TypeScript

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='19' AND `tutorial_submenu`='1163' AND `tutorial_status`=1 LIMIT 1

Ts Utility Types in TypeScript

TypeScript provides a set of built-in utility types that make it easier to manipulate and transform existing types. These utility types are designed to simplify common type transformations, enhancing code reusability and type safety.


Common Utility Types

  1. Partial
  2. Required
  3. Readonly
  4. Pick
  5. Omit
  6. Record
  7. Exclude
  8. Extract
  9. NonNullable
  10. ReturnType
  11. InstanceType
  12. Parameters
  13. ConstructorParameters

Detailed Explanation and Examples

1. Partial<T>

Makes all properties of type T optional.

typescript

interface User { id: number; name: string; email: string;}let partialUser: Partial<User> = { name: "Alice" };


2. Required<T>

Makes all properties of type T required.

typescript

interface User { id?: number; name?: string;}let user: Required<User> = { id: 1, name: "Alice" }; // Error if any property is missing


3. Readonly<T>

Makes all properties of type T readonly.

typescript

interface User { id: number; name: string;}const readonlyUser: Readonly<User> = { id: 1, name: "Alice" };// readonlyUser.id = 2; // Error: Cannot assign to 'id' because it is a read-only property


4. Pick<T, K>

Creates a type by picking specific properties K from type T.

typescript

interface User { id: number; name: string; email: string;}type UserInfo = Pick<User, "id" | "name">;let userInfo: UserInfo = { id: 1, name: "Alice" };


5. Omit<T, K>

Creates a type by omitting specific properties K from type T.

typescript

interface User { id: number; name: string; email: string;}type UserWithoutEmail = Omit<User, "email">;let user: UserWithoutEmail = { id: 1, name: "Alice" };


6. Record<K, T>

Creates a type with property keys of type K and values of type T.

typescript

type Role = "admin" | "user" | "guest";let userRoles: Record<Role, string> = { admin: "Alice", user: "Bob", guest: "Charlie",};

7. Exclude<T, U>

Excludes from T those types that are assignable to U.

typescript

type T = string | number | boolean;type Extracted = Extract<T, number | boolean>; // number | boolean


9. NonNullable<T>

Removes null and undefined from type T.

typescript

type T = string | null | undefined;type NonNull = NonNullable<T>; // string


10. ReturnType<T>

Extracts the return type of a function type T.

typescript

function getUser() { return { id: 1, name: "Alice" };}type UserType = ReturnType<typeof getUser>; // { id: number; name: string }


11. InstanceType<T>

Extracts the instance type of a class or constructor type T.

typescript

class User { id = 1; name = "Alice";}type UserInstance = InstanceType<typeof User>; // User


12. Parameters<T>

Extracts the types of the parameters of a function type T.

typescript

function login(username: string, password: string): class User { constructor(public id: number, public name: string) {}}type UserConstructorParams = ConstructorParameters<typeof User>; // [number, string]


Use Cases of Utility Types

  1. API Responses
    Use Partial or Pick for handling optional or specific fields in API responses.

  2. Immutable Data
    Use Readonly to enforce immutability in configurations or state objects.

  3. Type-safe Mappings
    Use Record for defining structured key-value mappings.

  4. Type-safe Filtering
    Use Exclude and Extract for filtering specific types.

  5. Dynamic Function Types
    Use ReturnType, Parameters, and ConstructorParameters for dynamic type extraction.


Best Practices

  1. Combine Utility Types
    Combine utility types for more advanced use cases.

    typescript

    type ImmutableUser = Readonly<Partial<User>>;

  2. Leverage Pick and Omit
    Use Pick and Omit to create lean and specific types for APIs or components.

  3. Avoid Overusing any
    Use utility types to create flexible yet type-safe structures instead of resorting to any.

  4. Keep Code Readable
    Use type aliases when utility types become too complex.


Conclusion

Utility types in TypeScript streamline the process of type manipulation and enable developers to write cleaner, safer, and more reusable code. By understanding these types, you can handle complex type scenarios effectively and improve your codebase's maintainability.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql