0

I have defined a function that I want to pass to .map:

export let disableTabsByRights = (permissions: string[], type: string) => permissions.includes(type);

export let disableTabsByUsers = (); 

Where this.tabs is array:

do(fn: Function) {
    this.tabs = this.tabs.map((item) => {
     item.disabled = fn(item.type); 
     return item;
    });
}

I want to call outside

do(disableTabsByRights(["VIEW"]));

Why it does not work for me?

So I want to change easy realizations?

3
  • 1
    How doesn't work? What happens and what do you expect to happen? Commented Sep 5, 2019 at 11:43
  • Seems to work for me at codesandbox.io/s/typescript-demo-sandbox-poekg Commented Sep 5, 2019 at 11:44
  • I have updated my question, there are some obvious changes Commented Sep 5, 2019 at 11:47

1 Answer 1

1

Your do function requires that a function is passed to it, but by passing disableTabsByRights(["VIEW"]), you're passing the return value of the invocation disableTabsByRights(["VIEW"], undefined) instead of a function.

Let's pass it an actual function instead, that takes a type string and returns a boolean value:

do(type => disableTabsByRights(["VIEW"], type))

would do the trick.

Otherwise, you could redefine the function as a higher-order function

export let disableTabsByRights = 
    (permissions: string[]) => 
    (type: string) => 
        permissions.includes(type);

So, now, we can call disableTabsByRights with a single parameter (permissions), and it will return another function with a single parameter (type) which already has a resolved permissions value.

To fully call this H-O function, you'd need to disableTabsByRights(["somePerm"])("someType")

Now you can use it as you first attempted:

do(disableTabsByRights(["VIEW"])); //now disableTabsByRights(["VIEW"]) returns a function.

As an aside, you could improve your code by specifying the exact shape of the function being passed in:

do(fn: (type:string) => boolean) { /*...*/ }

to enforce better type-safety.

Sign up to request clarification or add additional context in comments.

1 Comment

How does this trick work? Could you explain please, iterations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.