【问题标题】:Type checking strings instead of using instanceof类型检查字符串而不是使用 instanceof
【发布时间】:2018-12-12 12:42:21
【问题描述】:

假设我有一个执行 TCP 的库,响应可能会有所不同,一些响应表示错误。

使用 Error 对象没有多大意义,因为这很昂贵,而且堆栈跟踪与原始请求没有任何关系,因为错误会异步发生。

所以我能想到的最好的东西是一个简单的字符串,比如:

const makeRequest = function(err, result){

    if(err && err.code === 'Request timeout'){

    }

    if(err && err.code === 'Unauthorized'){

    }
};

如何允许用户使用 TypeScript 对字符串进行类型检查?

【问题讨论】:

    标签: node.js typescript tcp typescript-typings tsc


    【解决方案1】:

    您可以使用字符串文字字符串为错误代码提供类型检查(以及对错误代码的良好代码完成支持)。

    interface CustomError {
        code:'Request timeout' | 'Unauthorized'
    }
    
    const makeRequest = function(err : CustomError | null, result : any){
        if(err && err.code === 'Not an error'){ // This would be an error
    
        }
        if(err && err.code === 'Request timeout'){
    
        }
    
        if(err && err.code === 'Unauthorized'){
    
        }
    };
    

    如果每种类型的错误都有您想要提供的额外信息,您还可以将字符串文字类型与可区分的联合:

    interface TimoutoutError {
        code: 'Request timeout'
        time: number;
    }
    
    interface UnauthorizedError {
        code: 'Unauthorized'
        user: string;
    }
    
    type CustomError = TimoutoutError | UnauthorizedError;
    
    const makeRequest = function (err: CustomError | null, result: any) {
        if (err && err.code === 'Not an error') { // This would be an error
    
        }
        if (err && err.code === 'Request timeout') {
            err.time; // err is TimoutoutError
        }
    
        if (err && err.code === 'Unauthorized') {
            err.user // err is UnauthorizedError
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多