【问题标题】:Defining type of variable as number does not throw error even if value is string --TypeScript, Angular将变量类型定义为数字即使值是字符串也不会引发错误 --TypeScript, Angular
【发布时间】:2018-08-29 17:15:39
【问题描述】:

我刚开始研究角度和类型脚本。如果传递的参数不是数字类型但它失败了,我试图限制函数的执行。任何人都可以帮助我,或者如果我遗漏任何东西。谢谢。

/**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 中的类型是一个编译时概念。程序运行后,您就进入了 JavaScript 世界。
  • @Henry 所以我们不能像我写的那样写函数
  • 如果您尝试从组件类内部调用您的函数,则会捕获错误。但是由于您是从 HTML 调用它,因此那里可能没有类型检查。顺便说一句,我建议你输入 number 而不是 Number
  • @Frank ModicaI - 我也尝试将它输入为数字,它给出了相同的结果。
  • @MritunJay frank 的意思是你应该使用小写的类型编号,因为如果你使用大写形式,Typescript 中的原始类型是小写的,Typescript 会认为它是一个类或接口

标签: angular typescript


【解决方案1】:

如 cmets 中所述,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
}

【讨论】:

  • 投了反对票,因为他从 html 输入标签中获取值,该标签将标签绑定为文本。
  • @VaibhavKumarGoyal 公平的一点,我已经在更新中解决了这个问题。我也喜欢你用type 属性限制输入的方法
【解决方案2】:

编辑了您的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' );
    }
  }
}

【讨论】:

  • 其中一位用户给出了相同的解决方案,但他被否决了。不知道为什么
  • @MritunJay 是绝对可以使用的,因为来自 html 的任何内容都会根据 dom 对象属性类型以角度解释,因此将输入标签设置为文本,它最终会将所有内容返回为字符串
  • 输入标签作为文本它最终会将所有内容作为字符串返回,但我的方法期望参数为数字。那么它应该阻止该方法执行。
  • @MritunJay 请访问堆栈 biltz 编辑以查看它的工作情况
猜你喜欢
  • 2016-07-17
  • 2020-04-17
  • 2020-03-27
  • 2023-02-18
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多