Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 键入检查字符串,而不是使用instanceof_Node.js_Typescript_Tcp_Typescript Typings_Tsc - Fatal编程技术网

Node.js 键入检查字符串,而不是使用instanceof

Node.js 键入检查字符串,而不是使用instanceof,node.js,typescript,tcp,typescript-typings,tsc,Node.js,Typescript,Tcp,Typescript Typings,Tsc,假设我有一个执行TCP的库,响应可能会有所不同,一些响应表示错误 使用错误对象没有多大意义,因为这很昂贵,但是堆栈跟踪与原始请求没有任何关系,因为错误(如果发生)将异步发生 所以我能想到的最好的东西是一个简单的字符串,比如: const makeRequest = function(err, result){ if(err && err.code === 'Request timeout'){ } if(err && err.code

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

使用错误对象没有多大意义,因为这很昂贵,但是堆栈跟踪与原始请求没有任何关系,因为错误(如果发生)将异步发生

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

const makeRequest = function(err, result){

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

    }

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

    }
};

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

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

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

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