当我读取未知变量时,例如:req.body
或者JSON.parse()
知道它以某种方式格式化,例如:
type MyDataType = {
key1: string,
key2: Array<SomeOtherComplexDataType>
};
Run Code Online (Sandbox Code Playgroud)
我该如何转换它,以便以下工作:
function fn(x: MyDataType) {}
function (req, res) {
res.send(
fn(req.body)
);
}
Run Code Online (Sandbox Code Playgroud)
它总是失败告诉我:
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
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
我想,从技术上讲,这是正确的——你正在完善每一个值,并且只输入你知道是真实的值。
这是处理此类案件的适当方法吗?
归档时间: |
|
查看次数: |
430 次 |
最近记录: |