首页 > 解决方案 > 解析对象以匹配接口

问题描述

当我在我的任何 REST 端点(koa-router)中接收查询字符串时,查询字符串对象参数的每个值都是字符串(显然):

{
  count: "120",
  result: "true",
  text: "ok"
}

在我的代码库中,我有一个接口来表示查询字符串对象:

interface Params {
  count: number;
  result: boolean;
  text: string;
}

我想“解析”查询字符串对象,其中所有值都是字符串以匹配此接口。这样做的最佳做法是什么?

标签: javascripttypescript

解决方案


您需要将输入映射到预期的接口,这意味着将每个属性转换为预期的类型。

function toParams(input:any) : Params {
    var o = typeof input === "string" 
            ? JSON.parse(input) 
            : input;
    o.count = +o.count;
    o.result = o.result === "true" ? true : false;
    return o as Params;
}

您可以实例化Params具有所有属性集的默认实例,然后您可以遍历它们并验证每个属性在转换后的对象上的类型相同。

function toInterface(example:any, input:any) {
    Object.keys(example).forEach(function(key,index) {
        if (!input[key]) return;
        let exampleType = typeof example[key];
        let inputType = typeof input[key];
        if (exampleType !== inputType) {
            if (exampleType == "string") input[key] = input[key] + "";
            if (exampleType == "number") input[key] = +input[key];
            if (exampleType == "boolean") input[key] = input[key] === "true" ? true : false;
            // Any other cases
        }
    });
    return input;
}

推荐阅读