Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using named parameters JavaScript (based on typescript)

I have problems, when using named parameter in TypeScript, I know it is not supportetd the way I use it in TS. But how can I

TypeScript:

SomeFunction(name1: boolean, name2: boolean, name3: boolean, name4: boolean) //will occur only 1 time, so the change should be in typescript 

JavaScript:

$(function () {      ...SomeFunction({name1:false, name2:false, name3:false, name4:true}); //will occur 100 times     }); 

I was looking at(this did not work out):

Named parameters in javascript

How can I add optional named parameters to a TypeScript function parameter?

What can I do in TypeScript, to use named parameters in JavaScript?

What I wonder is, that VS2015 did not show a syntax error when using named parameter the way I used it in TypeScript ...

ps.: I use TS 2.1

like image 893
user7425470 Avatar asked Feb 08 '17 09:02

user7425470


People also ask

What is named parameter in TypeScript?

Even though there is technically no such thing as a named parameter in TypeScript (or JavaScript), the language offers a syntax that makes it possible to use a very similar functionality! Named arguments make life much easier. They allow you to play with function arguments almost like you play with letters in Scrabble.

How do you pass a function name as parameter in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

Does JavaScript support named arguments?

JavaScript, by default, does not support named parameters. However, you can do something similar using object literals and destructuring. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, {} , even if you have default values set up.

How do you pass optional parameters in TypeScript?

In Typescript, making optional parameters is done by appending the “?” at the end of the parameter name in the function when declaring the parameters and the parameters which are not marked with “?” i.e not optional parameter are called as default parameters or normal parameters where it is must and compulsory to pass ...


1 Answers

True named parameters don't exist in JavaScript nor in TypeScript but you can use destructuring to simulate named parameters:

interface Names {     name1: boolean     name2: boolean     name3: boolean     name4: boolean }  function myFunction({name1, name2, name3, name4}: Names) {     // name1, etc. are boolean } 

Notice: The type Names is actually optional. The following JavaScript code (without typing) is valid in TS:

function myFunction({name1, name2, name3, name4}) {     // name1, etc. are of type any } 
like image 185
Paleo Avatar answered Sep 18 '22 13:09

Paleo