Sobes.tech
Middle

Explain the differences between these TypeScript utility types and their use cases: ```typescript type someType1<T extends object> = Partial<T>; type someType2<T extends object> = T[keyof T]; type someType3<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; type SomeType4<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>; ```

sobes.tech AI

Answer from AI

  • Partial<T> — makes all properties of type T optional. It is used when you need to create an object where only some properties of the original type are specified.

  • T[keyof T] — is an index access that returns a union of all property value types of object T. For example, if T is {a: string; b: number}, then T[keyof T] will be string | number.

  • Pick<T, Exclude<keyof T, K>> — selects all properties from type T except those specified in K. Exclude removes keys K from all keys of T, and Pick selects the remaining. This is equivalent to Omit<T, K>.

  • Omit<T, K> & Partial<Pick<T, K>> — creates a type where properties from K become optional, and the rest remain required. This is useful when you want to make some properties optional while keeping others mandatory.

Example of using SomeType4:

interface User {
  id: number;
  name: string;
  email: string;
}

// Make email optional
type UserWithOptionalEmail = SomeType4<User, 'email'>;

const user1: UserWithOptionalEmail = { id: 1, name: 'Alice' }; // email is optional