Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking arrow functions in typescript or javascript

I stumble upon below code of arrow function in a book "Getting Started with Angular, Second Edition".

let isPrime: (n: number) => boolean = n => { 
// body 
};

I want to confirm correctness of this breakdown.

  1. let isPrime = function name "isPrime"
  2. (n: number) = input parameter number "n"
  3. => boolean = arrow function to check boolean (a place to put the logic)
  4. =n = i don't get this part. does this mean if i put "logic to find prime number in third step" and true, you get "n" that satisfy my logic?
  5. => {} = i can put return or other logic here for final process.

The last question is how many arrow functions is too much for chaining or curring?

I believe @Fenton give clear explanation for my understanding.

@Sebastien gives me answer that make me realise my wrong interpretation to arrow function ; equal and arrow sign doesn't always point to function, and can represent datatype too.

below is combined version of my accepted answer.

Types

Now let's describe the types for this function, which are that is takes in a number, and gives back a boolean.

//correct usage : return boolean
let isPrime: (n: number) => boolean = n => { 
    // body
    return true
};

//incorrect usage
let isPrime: (n: number) => boolean = n => { 
    // body
    return "wrong"
};

Simple

I suppose that I would write it as below, unless I had a good reason to use an arrow function!

//correct usage : return boolean
function isPrime(n: number): boolean {
    // body
    return true;
}
//incorrect usage
function isPrime(n: number): boolean {
    // body
    return "wrong";
}

My final test is like this.

let isRightLogic: (n: number) => { host: boolean } = n => { 
   return { host: true };
}
console.log(isRightLogic(1)); // always return true but you get the idea.
like image 615
phonemyatt Avatar asked Sep 23 '26 09:09

phonemyatt


1 Answers

In the code you posted, (n: number) => boolean is the type signature for the function being created. The function itself is just

n => {
  // body
}

The n is the parameter name, as indicated by the type signature. Thus Typescript knows that parameters passed to the function should be numbers, and that the return value from the function will be true or false.

The symbol isPrime is not really the function name in a formal sense; it's a variable whose value happens to be that function.

In plain JavaScript, the variable declaration would be juss

let isPrime = n => {
  // body
};
like image 181
Pointy Avatar answered Sep 24 '26 23:09

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!