You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 2中如何在TypeScript里检查API返回对象的类型?

How to check if an API response object is of type ErrorDTO in TypeScript?

I'm developing an Angular 2 web application and currently implementing exception handling. I've created a model that matches the structure of the server's returned object (ERROR DTO). Here's my error handler code:

protected handleError(error, continuation: () => Observable<any>) {
    if (error.status == 401) {
        this.appContextService.redirectForLogin();
    } else if (typeof error == ErrorDTO) {
        return Observable.throw(error);
    } else {
        return Observable.throw(error);
    }
}

I need to know how to check if the received error object from the API is of type ErrorDTO in TypeScript.


Great question! The issue with your current code is that typeof in TypeScript (and vanilla JavaScript) only detects basic built-in types like string, number, object, or function—it can't verify if an object is an instance of your custom ErrorDTO class. Let's walk through the best solutions based on how you're working with the API response:

1. If you're explicitly creating ErrorDTO instances from the API response

If you're converting the API's JSON data into actual ErrorDTO instances (e.g., using a constructor or factory method), you can use the instanceof operator. This checks if the object was created with the ErrorDTO constructor:

else if (error instanceof ErrorDTO) {
    return Observable.throw(error);
}

This works cleanly because instanceof validates the object's prototype chain against your class.

2. If you're working with plain JSON objects (most common for APIs)

APIs return JSON, which gets parsed into plain JavaScript objects—these aren't instances of your ErrorDTO class, even if their structure matches. For this scenario, you'll need a type guard function to validate the object's properties:

First, define a type guard that checks for the unique properties of your ErrorDTO:

function isErrorDTO(obj: any): obj is ErrorDTO {
    // Replace these checks with the actual properties your ErrorDTO uses
    return obj && typeof obj === 'object' &&
           'errorCode' in obj &&
           'errorMessage' in obj &&
           typeof obj.errorCode === 'number' &&
           typeof obj.errorMessage === 'string';
}

Then use it in your error handler:

else if (isErrorDTO(error)) {
    // TypeScript now recognizes 'error' as ErrorDTO in this block
    return Observable.throw(error);
}

This not only validates the object's structure but also tells TypeScript to narrow the type of error to ErrorDTO inside that conditional block, giving you proper autocompletion and type safety.

3. Bonus: Automatically convert JSON to class instances with class-transformer

If you want to avoid manual property checks, you can use the class-transformer library to convert API JSON responses into actual ErrorDTO instances.

First, decorate your ErrorDTO class to map JSON properties:

import { Expose } from 'class-transformer';

export class ErrorDTO {
    @Expose()
    errorCode: number;

    @Expose()
    errorMessage: string;
}

Then parse the API response into an instance:

import { plainToInstance } from 'class-transformer';

// When handling the API error response
const errorInstance = plainToInstance(ErrorDTO, errorResponse);

Now you can safely use errorInstance instanceof ErrorDTO in your handler.

A quick side note: Your current else if and else blocks do the exact same thing, so once you have the correct type check, you can simplify that logic to avoid redundancy.

内容的提问来源于stack exchange,提问作者Niranjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:38:10