簡體   English   中英

將變量定義為數字,即使值是字符串--TypeScript,Angular也不會引發錯誤

[英]Defining type of variable as number does not throw error even if value is string --TypeScript, Angular

我剛剛開始研究角度和類型腳本。 如果傳遞的參數不是數字類型,但是失敗了,我試圖限制函數的執行。 任何人都可以在這方面幫助我,或者如果我缺少任何幫助。 謝謝。

/ ** TS文件** /

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  txtVal: number;

  getval(val:number){
    console.log('val', this.txtVal)
  }
}

/ HTML /

<input type="text" [(ngModel)]= "txtVal">
<button (click)="getval(txtVal)">Get Val</button>

https://stackblitz.com/edit/angular-d9hwsi?file=src%2Fapp%2Fapp.component.html

如注釋中所述,TypeScript中的類型定義是編譯時檢查。 此編譯時檢查僅對.ts代碼有效,因此Angular綁定未針對類型進行驗證。

如果希望在運行時限制執行,則需要手動執行

getval(val:Number){
  if (typeof val !== "number") {
     throw new Error("Value is not a number");
  }

  console.log('val', this.txtVal)
}

或者,如果您只想記錄錯誤並且不干擾執行

getval(val:Number){
  if (typeof val !== "number") {
     console.error("Value is not a number");
     return;
  }

  console.log('val', this.txtVal)
}

但是,由於要從輸入字段傳遞值,因此您可能想測試用戶輸入的值是否可以轉換為數字。

getval(val: string){
  const numberValue = Number(val);
  if (numberValue === Number.NaN) {
     throw new Error("Value is not a number");
  }

  // Do stuff
}

編輯了您的stackbiltz 。請更改html本身的綁定為

<input type="text" [(ngModel)]= "txtVal">
<button (click)="getval(txtVal)">Get Val</button>

那么如果您使用typeOf,它將返回您的類型為數字

import { Component } from '@angular/core';
import{Observable} from 'rxjs';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  txtVal :any;
  tet: number;



     getval(val :number){
    if(Number.isNaN(parseInt(this.txtVal)))
    {
      return;
    }
    else{
        console.log('couldn\'t convert' );
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM