首页 文章

TypeScript - 检查类型

提问于
浏览
2

我想知道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 回答

  • 1

    如果代码是这样的

    myMethod(argument: string) {
    

    然后你不需要检查使用类型的类型,因为在打字稿中你会得到错误,如果你这样做

    let strVar : string;
    strVar = 10;//error (means you cannot assign type other then string, same gose for method)
    

    在angular中你可以设置它以避免通过在config中设置选项转换为 any 类型

    {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2015", "dom" ],
        "noImplicitAny": true,//not allow implicit conversion to any type
        "suppressImplicitAnyIndexErrors": true
      }
    }
    

    点击这里:https://angular.io/guide/typescript-configuration

相关问题