我想知道TypeScript中的类型保护,如果在方法签名中只定义了一种类型,则需要使用它们 . TypeScript文档中的所有示例仅涉及具有联合类型的情况,例如:
myMethod(argument: string | number) {
if (typeof argument === 'string') { // do my thing }
if (typeof argument === 'number') { // do my thing }
但是我看到人们在强类型时使用typeof:
myMethod(argument: string) {
if (typeof argument === 'string') { // do my thing }
你认为这是一个好方法吗?如何检查数据,尤其是编译期间不可用的数据(例如从API endpoints )?
1 回答
如果代码是这样的
然后你不需要检查使用类型的类型,因为在打字稿中你会得到错误,如果你这样做
在angular中你可以设置它以避免通过在config中设置选项转换为
any
类型点击这里:https://angular.io/guide/typescript-configuration