Search code examples
functionparametersannotationsarguments

What programming language has a colon "inside" and "after" the parameter of a function


I came across this function and I've been searching for the programming language that has this syntax:

function getDiscount(items: Item[]): number {

   if(items.length === 0){
      throw new Error("Items cannot be empty");
   }

   let discount = 0;

   items.forEach(function(item) {
      discount += item.discount;
   })

   return discount/100;}

The parameter is delimited by a colon (:), and then the parameter is followed by another colon. I tried to run the code on the console but I'm getting an error "Uncaught SyntaxError: Unexpected token ':'"

The closest that I could find is Python's function annotation, however, the parameter is followed by an arrow instead of a colon.

I would also like to know what the code on the first line means - the parameter and what follows the parameter. My understanding is that the argument that will be passed will be inserted into an array and the data type of what will be returned is a number. Please correct me if I'm wrong.


Solution

  • This code is written in TypeScript (https://www.typescriptlang.org), which is a superset of JavaScript. TypeScript code is valid JavaScript with added types.
    Actually, if you removed the type annotations you could run this code in browser console:

    function getDiscount(items) {
    
       if(items.length === 0){
          throw new Error("Items cannot be empty");
       }
    
       let discount = 0;
    
       items.forEach(function(item) {
          discount += item.discount;
       })
    
       return discount/100;
    }
    

    TypeScript needs to be converted into JavaScript so it can be used in a browser or NodeJS. The conversion process is known as 'transpiling', which is similar to compiling but is more like transformation from one human readable language to another, rather than the typical conversion from a human readable to machine readable. (I updated this description as suggested by Caius Jard)

    Type annotations in the definition of the function mean that it takes an array of items of type Item as an argument and returns type number. From the code we can say that the type Item is an object which has at least one key, discount, of type number. This code will iterate over the array of Item's and return the sum of all discounts.