1. Use a Generic Utility Function
Using a generic type allows the function to be more flexible.
interface User {
  name: string;
  age: number;
  address?: string;
}
const updateUser = <T extends Partial<User>>(user: T): void => {
  console.log(user);
};
updateUser({ name: 'John' });
2. Add Default Values
You can provide default values to ensure all properties are initialized.
interface User {
  name: string;
  age: number;
  address?: string;
}
const updateUser = (user: Partial<User> = {}): void => {
  console.log(user);
};
updateUser({ name: 'John' });
updateUser(); // Handles no argument gracefully
3. With Type Aliases
Instead of directly using Partial, define a type alias for clarity.
interface User {
  name: string;
  age: number;
  address?: string;
}
type UpdateUserInput = Partial<User>;
const updateUser = (user: UpdateUserInput): void => {
  console.log(user);
};
updateUser({ name: 'John' });
4. With Class and Method
Implementing the updateUser functionality within a class for better encapsulation.
interface User {
  name: string;
  age: number;
  address?: string;
}
class UserManager {
  updateUser(user: Partial<User>): void {
    console.log(user);
  }
}
const userManager = new UserManager();
userManager.updateUser({ name: 'John' });
5. Use Functional Style with Default Parameter
Inline defaults for optional fields can make the function compact.
interface User {
  name: string;
  age: number;
  address?: string;
}
const updateUser = ({ name = '', age = 0, address }: Partial<User>): void => {
  console.log({ name, age, address });
};
updateUser({ name: 'John' });
6. Inline Type Definition Without Interface
If the User interface is simple and used only once, inline types can be used.
const updateUser = (user: { name?: string; age?: number; address?: string }): void => {
  console.log(user);
};
updateUser({ name: 'John' });
7. Use Record for Dynamic Properties
If User is dynamic, use Record<string, any>.
const updateUser = (user: Record<string, any>): void => {
  console.log(user);
};
updateUser({ name: 'John', age: 25 });
8. Combine Validation with Type Guard
Enhance the function with runtime validation.
interface User {
  name: string;
  age: number;
  address?: string;
}
const isUser = (user: Partial<User>): user is Partial<User> => {
  return typeof user.name === 'string';
};
const updateUser = (user: Partial<User>): void => {
  if (isUser(user)) {
    console.log(user);
  } else {
    console.error('Invalid user');
  }
};
updateUser({ name: 'John' });
Each approach has its own use case depending on the requirements for flexibility, validation, and structure.
No comments :
Post a Comment