javascript - 解析对象以匹配接口
问题描述
当我在我的任何 REST 端点(koa-router)中接收查询字符串时,查询字符串对象参数的每个值都是字符串(显然):
{
count: "120",
result: "true",
text: "ok"
}
在我的代码库中,我有一个接口来表示查询字符串对象:
interface Params {
count: number;
result: boolean;
text: string;
}
我想“解析”查询字符串对象,其中所有值都是字符串以匹配此接口。这样做的最佳做法是什么?
解决方案
您需要将输入映射到预期的接口,这意味着将每个属性转换为预期的类型。
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;
}
推荐阅读
- drupal - Drupal 8 站点陷入维护
- ios - 无法在进程中执行支持代码来读取 Objective-C 类数据。在真正的 iPhone 设备上
- javascript - 为什么从其他文件导入组件会导致“Invariant Violation: Element type is invalid”错误?
- sql - Listagg 分区而不是 Group By
- c++ - 微型过滤器从用户模式应用程序接收常量值
- javascript - 为什么在我安装节点 10.1.0 之后它说安装的版本是 5.6.0?
- c - 如何使用父进程和两个子进程将字符串写入文件?
- html - 如何在css中调整图像大小并适合容器(div)
- rabbitmq - 监听器使用时从 RabbitMQ 中删除消息。无法确定回复消息异常
- scala - 删除 GraphX 中没有出边的顶点