您可以使用字符串文字字符串为错误代码提供类型检查(还可以为错误代码提供良好的代码完成支持)。
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
}
};