angular - 如何让 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 以防止在这样的场景中执行?
解决方案
打字稿只是警告你,有些事情是不对的。它仍然可以编译,您仍然可以运行代码并且它可以工作,但它并不打算那样工作。
那么如何检查输入是否正确呢?
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 可用于任何地方检查某物是否是有效颜色
推荐阅读
- asp.net-core - NetCore 3.1 中操作的自定义 URL
- dart - PayPal Orders v2:订单的approvalurl(“checkoutnow?token..”)返回302重定向
- jquery - 为什么柏树调用动画甚至调用都不起作用?
- c++ - 将字符串拆分为向量
- android - 如何获取 Unitech PA760 的 Android SDK?
- c# - EF6 与 MySQL - 日期时间中的格式异常
- python - Django 应用程序的错误配置错误
- ios - 弹出 iOS UINavigationController 时如何调用方法?
- html - 孩子不尊重其父母的大小 SwiftUI
- linux - .Net Core 3.1 是否具有检测 GPIO 引脚更改的事件驱动方法?