作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我读取未知变量时,例如:req.body
或 JSON.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
.
最佳答案
我可以让它工作的一种方法是遍历正文并复制每个结果,例如:
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/
我是一名优秀的程序员,十分优秀!