gpt4 book ai didi

express - 如何将混合类型转换为对象类型

转载 作者:行者123 更新时间:2023-12-04 21:07:58 25 4
gpt4 key购买 nike

当我读取未知变量时,例如:req.bodyJSON.parse()并知道它以某种方式格式化,例如:

type MyDataType = {
key1: string,
key2: Array<SomeOtherComplexDataType>
};

我该如何转换它,以便以下工作:
function fn(x: MyDataType) {}
function (req, res) {
res.send(
fn(req.body)
);
}

它一直失败告诉我: req.body is mixed. This type is incompatible with object type MyDataType .

我认为这与 Dynamic Type Tests 有关但要弄清楚如何...

最佳答案

我可以让它工作的一种方法是遍历正文并复制每个结果,例如:

if (req.body && 
req.body.key1 && typeof req.body.key2 === "string" &&
req.body.key2 && Array.isArray(req.body.key2)
) {
const data: MyDataType = {
key1: req.body.key1,
key2: []
};
req.body.key2.forEach((value: mixed) => {
if (value !== null && typeof value === "object" &&
value.foo && typeof value.foo === "string" &&
value.bar && typeof value.bar === "string") {
data.key2.push({
foo: value.foo,
bar: value.bar
});
}
});
}

我想,从技术上讲,这是正确的 - 您正在完善每个值,并且只输入您知道正确的值。

这是处理此类案件的适当方式吗?

关于express - 如何将混合类型转换为对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41193395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com