2

this happened to me now multiple times, so I want to ask if I´m doing something wrong or Typescript / Angular really dont do it. From my understanding one of the biggest strengths is the type declaration (interface) for variables, parameters and so on.

Today I had this problem:

A simple switch button:

<p-selectButton [options]="posLayouts" (onChange)="handle($event)" [(ngModel)]="pageSize"></p-selectButton>

The variables:

pageSize: number;

  posLayouts: SelectItem[];

  //On mistake I setted the value here as a string
  this.posLayouts.push({label:'1 Woche', value: '1'});
  this.posLayouts.push({label:'3 Wochen', value: '3'});

In the change function I simply call another function with the value out of posLayouts.

handle(e){getPager(this.pageSize)}
  getPager(pageSize: number = 3){
    let totalPages: number;
    totalPages = 23 + pageSize -1
    console.log(totalPages)
}

console.log(), returns than eiter 230 or 232 instead of the wanted 23 or 25. It takes pageSize as string. This type errors are hard to find, this time I had luck cause it was easy to find... Neither Angular or tslint or my editor tells me anywhere that I cant store a string in a number variable.

For my understanding, typescript should check for the compatiblity or does Angular somehow disable the listening here ? Or I´m doing something wrong ?

1 Answer 1

2

TypeScript types are only used by development tools (linter, autocompletion, ...).
For runtime all code is converted to JavaScript and there is no type information available anymore.
So for user input or other sources of data from outside your code, you need to make sure yourself the data conforms to the types you expect.

Sign up to request clarification or add additional context in comments.

2 Comments

Hm it´s not what I wanted to hear but thank you. So user-input has still to be type checked by my own.
Yes, types are only for development and the build process (more efficient tree-shaking). If they would keep type-checks everywhere in the generated JS code, the performance impact would be way too high.

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.