2016-12-16 21 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 
     }); 
    } 
    }); 
} 

我想,從技術上講,這是正確的 - 你正在提煉每一個單一的價值,只會把你知道的事情變爲現實。

這是處理這類案件的適當方式嗎?

相關問題