Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a mixed type to an object type

When I read an unknown variable, eg: req.body or JSON.parse() and know it is formatted in a certain way, eg:

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

how can I convert it, so that the following works:

function fn(x: MyDataType) {}
function (req, res) {
  res.send(
    fn(req.body)
  );
}

It keeps failing telling me that: req.body is mixed. This type is incompatible with object type MyDataType.

I assume this has something to do with Dynamic Type Tests but figure out how...

like image 353
William Becker Avatar asked Dec 16 '16 22:12

William Becker


1 Answers

One way I can get this to work is by iterating through the body and copying every result over, eg:

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

I guess, technically this is correct - you are refining every single value and only putting in what you know to be true.

Is this the appropriate way of handling these kinds of cases?

like image 78
William Becker Avatar answered Dec 27 '22 04:12

William Becker