Error "Argument of type is not Assignable to" in function with Rest parameters in Typescript

Asked

Viewed 54 times

0

I got a guy Role which must be a roles object key and a function that returns all keys:

export type Role = keyof typeof roles;

export function allRoles(): Role[] {
  return Object.keys(roles) as Role[];
}

And the next decorator:

export const Roles = (...roles: Role[]) => setMetadata('roles', roles);

However, when trying to use the decorator as @Roles(allRoles()), Typescript informs that there is error in the types:

Argument of type '('Role1', 'Role2')' is not assignable to the parameter of type 'Role1 | Role2'.

  • What is this function Roles? Could [Edit] the question to include your signature?

  • I added, the Roles function simply adds roles in the Multimedia

  • What do you want Roles receive, in fact? An array whose elements are the keys of roles?

  • Exactly, Roles must receive an array of Roles, the items in this array are keys of an object, which in this case is the keyof typeof roles

1 answer

4


The problem is that the guy Role[] is different from the type expected by the construction (...roles: Role[]).

The guy Role[] means any array whose elements are attributable to the type Role.

Already (...roles: Role[]) is a syntactic construct that is used to define the type of a function that accepts parameters Rest, that is, a function with aridity varied.

This means that the function does not accept an array in the first argument (as you are passing), but rather a varied number of arguments of the type Role which together form an array of the type Role[].

Then you need to change the type of the function so that it is no longer a variadic function:

function Roles(...roles: Role[]) {
  // ...
}

Making it a function that accepts only one argument - an array of Roles:

function Roles(roles: Role[]) {
  // ...
}

See working on Typescript playground.


Another option would be to use Function.prototype.apply or the spreading operator at the return of getRoles(), but semantically speaking, I do not believe they are correct. Changing the expected type of function, in this case, seems to me the most appropriate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.