2016-12-16 23 views
4

当我读到一个未知的变量,例如: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但弄清楚如何...

回答

2

一种方法我能得到这个工作是通过身体迭代和每个结果在复制,如:

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 
     }); 
    } 
    }); 
} 

我想,从技术上讲,这是正确的 - 你正在提炼每一个单一的价值,只会把你知道的事情变为现实。

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

相关问题