Node.js 键入检查字符串,而不是使用instanceof
假设我有一个执行TCP的库,响应可能会有所不同,一些响应表示错误 使用错误对象没有多大意义,因为这很昂贵,但是堆栈跟踪与原始请求没有任何关系,因为错误(如果发生)将异步发生 所以我能想到的最好的东西是一个简单的字符串,比如: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
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
}
};