代码之家  ›  专栏  ›  技术社区  ›  Alexander Mills

类型检查字符串而不是使用instanceof

  •  1
  • Alexander Mills  · 技术社区  · 6 年前

    使用错误对象没有多大意义,因为这样做很昂贵,但是堆栈跟踪与原始请求没有任何关系,因为错误将以异步方式发生。

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

    const makeRequest = function(err, result){
    
        if(err && err.code === 'Request timeout'){
    
        }
    
        if(err && err.code === 'Unauthorized'){
    
        }
    };
    

    如何允许用户使用TypeScript检查字符串?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    6 年前

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

    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
        }
    };