Home > Mobile >  It is a good practice type object pass as argument for a function with your parameter already typed?
It is a good practice type object pass as argument for a function with your parameter already typed?

Time:05-20

I am working on a TypeScript project and I need to create a service function. So I create with this format:

interface UserService {
  name: string;
  age: number;
  complement: string;
}

const userService = ({ name, age, complement }: UserService) => {
  // CODE
};

Thinking about the best practices in TypeScript, is it OK to use the second format, or do I need to type the object that I will pass to as the first format?

First format:

 const user: UserService = {
  name: '',
  age: 0,
  complement: ''
}

Second format:

const user = {
      name: '',
      age: 0,
      complement: ''
    }

And in my controller, I call the function like this:

userService(user);

CodePudding user response:

A selection of reasons why you should always use the first format:

  • Documentation; the next person who reads the code (including you, in the future) can see exactly what you expected that object to be.

  • Your IDE can help you autocomplete the property names, because it can also see exactly what you expected that object to be, so it knows what properties it should have.

  • You get excess property checking, so you don't include properties that aren't actually needed in a UserService.

    That can be beneficial for avoiding accidents, but also helps out if you later change UserService, renaming or removing some properties, then the compiler can lead you right to the objects where the change is needed (rather than the function calls they're used in).

  • You get clearer error messages, closer to the error, when the compiler knows what type an object is supposed to be when it's defined rather than when it's used.

    Compare how much harder it is to figure out the problem from:

    Argument of type '{ name: string; age: number; compliment: string; }' is not assignable to parameter of type 'UserService'.
      Property 'complement' is missing in type '{ name: string; age: number; compliment: string; }' but required in type 'UserService'.(2345)
    

    than from:

    Type '{ name: string; age: number; compliment: string; }' is not assignable to type 'UserService'.
      Object literal may only specify known properties, but 'compliment' does not exist in type 'UserService'. Did you mean to write 'complement'?(2322)
    

    Yes, you did mean to write complement!

Playground

Although frankly, if you only use that value when you call the service, you'd get all the same benefits without having to write : UserService if you inlined the object creation:

userService({
  name: '',
  age: 0,
  complement: ''
});

  • Related