首页 > 解决方案 > 如何让 Typescript 抛出运行时错误?

问题描述

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 constructor() {
   console.log(this.getColor(1000))
}
getColor(c:String) {
  return c
}
}

我的文本编辑器在 1000 下方放了一条红线,上面写着:“1000”类型的参数不可分配给“字符串”类型的参数。ts(2345)

好的...但是我的应用程序仍在执行,我可以在控制台上看到结果。

有什么方法可以制作 Angular 和/或 Typescript 以防止在这样的场景中执行?

标签: angulartypescript

解决方案


打字稿只是警告你,有些事情是不对的。它仍然可以编译,您仍然可以运行代码并且它可以工作,但它并不打算那样工作。

那么如何检查输入是否正确呢?

function example (color: string): void {
  if (typeof color !== 'string') {
    throw Error() // you can put your error message in here
  }
}

更新 15.01.2022

我建议稍微改变一下我的上述解决方案。使用新的打字稿功能,您可以编写

interface IColor extends string

function isColor(color: any): color is IColor {
  if (typeof color !== 'string') return false
  return true
}

function example (input: string): void {
  if (isColor(input)) {
    throw Error() // you can put your error message in here
  }
  // everything you wanna do here
}

与我的旧建议相比的一些优点:

  • IColor 可更改或可扩展为数字或十六进制
  • isColor 可用于任何地方检查某物是否是有效颜色

推荐阅读