1

My constructor in angular2 has a lot of parameters which are optional .Its like a search construct. When passing parameters , how can i say this parameters is this ? Suppose if there is first-name,last-name,age,sex which are all optional. I have to just pass sex without passing any other things. It looks like passing a parameter with a name. I dont want to pass null and by pass things.

Thanks

Ben Racicot
  • 5,332
  • 12
  • 66
  • 130
Janier
  • 3,982
  • 9
  • 43
  • 96

2 Answers2

1

You can use one 'options' parameter:

const obj = new User({age: 28});
-2

If its just a simple typescript class, all you have to do is add question marks after any optional parameters. So intead of

constructor(x: number, abc: string, z:number)

You could just do

constructor(x:number, abc?:string, z?:number) 

Which would make the last two parameters optional.

If you're talking about making optional parameters in the constructor of a component, directive, or injectable service, you can import the "Optional" decorator and preface any injected classes with that. I.e :

constructor( @Optional() private win: WindowService) {
diopside
  • 2,981
  • 11
  • 23
  • my question is about how to pass only few optional parameters – Janier Aug 22 '17 at 19:45
  • And that's exactly what my answer was about... ? What are you not understanding? – diopside Aug 22 '17 at 19:46
  • How can invoke the constructor by passing only Z without passing x? – Janier Aug 22 '17 at 19:55
  • Oh. In typescript you have to specify "undefined" if there is a "gap" in your parameters list. The better thing to do would be to pass a single object as a parameter, and then create an interface for that object. export interface MyInterface { property1: number; property2?: any; property3? number; property4: string; } and then you can just pass the parameters you have available without having to specify if any are missing. let abc = new MyClass({property1: 123, property5: "abc"}); and not have to worry about any in between. – diopside Aug 22 '17 at 19:56
  • I am looking for something like named parameters rather than undefined or null. – Janier Aug 22 '17 at 19:58