使用 is 收缩接口返回数据的类型

81 阅读1分钟

使用 is 使得接口返回的数据获得类型校验

type Evaluation = {
    "total": number;
    "avgScore": number;
    "scorePer": number;
    "targetPer": number;
    "compare": "-1" | "0" | "1";
    "itemBOS": {
        "itemName": string;
        "avgScore": number;
        "avgScoreRate": number;
        "total": number;
        "avgItemScoreRate": number;
    }[];
} | undefined

const isEvaluation = (res: Evaluation): res is Evaluation => {
    if (res?.itemBOS) {
        return true;
    }
    return false;
}

编译结果:

"use strict";
const isEvaluation = (res) => {
    if (res === null || res === void 0 ? void 0 : res.itemBOS) {
        return true;
    }
    return false;
};

与直接使用断言的最大区别是,使用is收缩变量的类型,不仅能够推断变量的类型,还能生成运行时代码,从而判断类型。而断言在运行时是不存在的。

使用:

function getJSON() {
    API.getJSON().then((res: any) => {
        if (isEvaluation(res) && res) {
            // 在此代码块中,res的类型被推断为Evaluation,并且运行时改代码块中要求res必须有itemBOS属性
        } else {
            resetEvaluation();
        }
    }).catch(() => resetEvaluation())
}