1

I have this angular2 typescript array

part of my angular file

export class ParametersForm {
  myForm: ControlGroup;
  systemParameters: AbstractControl;
  arr: number[];

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      "realisations" : [""],
      "numConstSteps" : [""],
      "timeHorizon": [""],
      "continuationStep" : [""],
      "continuationStepSign" : [""],
      "numberOfModelParameters" : [""],
      "systemParameters" : [],
      "param" : [""],
      "netLogoFile" : [""],
      "numberOfModelVariables" : [""],
      "restrictOperator" : [""],
      "liftOperator" : [""],
      "xInitial" : [""]

    });
    this.arr = [];
    this.systemParameters = this.myForm.controls["systemParameters"];
  }
  addToArray(event, value: any): void {
    if (event.which === 13) {
      this.arr.push(value);
      (<Control>this.systemParameters).updateValue("");
    }
  }

  deleteItem(value: any): void {
    let pos = this.arr.indexOf(value);
    this.arr.splice(pos, 1);
    console.log(this.arr);
  }
  onSubmit(form: any): void {
    console.log(this.arr);
    form.systemParameters = this.arr;
    console.log("your submitted value:", form);
  }

}

you can see arr:number[]

the way i read it, it says, this arr is an array of type number - expects numbers in it

then how come i can enter a string in it?

here is a plunker showing this (check in console after you press enter in input field)

plunkr

is that normal or?

2 Answers 2

4

Sadly that is expected, arrays do have types, but TypeScript makes an exception for any values. This is probably for backwards compatibility to JS.

For example this will work fine, sadly.

arr: MyClass[];
func(value: any) {
    this.arr.push(value);
}

This however won't work:

arr: MyClass[];
func(value: string) {
    this.arr.push(value);
}

So avoid using anyto mitigate this problem.

If you're talking about runtime problems you can use a typeof to check it's type.

addToArray(event, value: number): void {
   if (event.which === 13 && typeof value == 'number') {
        this.arr.push(value);
        (<Control>this.systemParameters).updateValue("");
     }
}
Sign up to request clarification or add additional context in comments.

3 Comments

exchanging value: any with value: number still lets empty strings in my array.
Yeah, I see where the problem lies. You can always check the type at runtime. I'll edit my answer.
even though this works how do i disable number field from letting me input e? it gives me NaN in the array if left like this. You can check updated plunker
3

Types are only for the compiler and the developer during development.

As soon as you tanspile your ts files, the type information is lost. We can say they are just an illusion.

TypeScript doesn't prevent anything during runtime. In fact there is no such thing as TypeScript during runtime. Your plain old JavaScript is running the same way as before TypeScript was even born.

So you can only do this in this case:

addToArray(event, value: any): void {
    if (event.which === 13 && value) {
        this.arr.push(value);
        (<Control>this.systemParameters).updateValue("");
    }
}

To further emphasize the point that there are no type safety during runtime, just check the TypeScript Playground. On the left hand side you see the TypeScript code, on the right hand side you see the generated JS code.

Try out some things (interface declarations etc, using types in general) and see how they disappear from JavaScript.

4 Comments

This isn't really a problem because of runtime vs compile time, though. The compiler explicitly allows this! You would expect a compile error in this case.
Yes, I know. I have a feeling though that there is a deeper misunderstanding in this question :) Even if he uses number for example in the parameter and call that method from an angular template from HTML with addToArray($event, "HEY THIS IS DEFINITELY NOT A NUMBER"). It will call that method without any problem. And the programmer will debug the code and will be wondering why is it a string if the parameter says number
@SzabolcsDézsi so you are saying there is no way around this? adding && value clearly works but even when i set value: number still it got accepted which is what you said really. this is confusing.
Think about it like this: the typescript compiler will try his best to give the illusion that it's a number array. But it can't predict what a value will end up being during runtime. By the way, another thing: var num: number = null; is perfectly valid. Anything can be null.

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.