Doomenik
Doomenik

Reputation: 866

Typescript / Angular Type declaration useless?

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 ?

Upvotes: 2

Views: 414

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657338

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.

Upvotes: 2

Related Questions