How to convert a mixed type to an object type

When I read an unknown variable, for example: req.bodyor JSON.parse(), and I know that it is formatted in a certain way, for example:

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

how can i convert it, so the following works:

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

You can not tell me that: req.body is mixed. This type is incompatible with object type MyDataType.

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

+4
source share
1 answer

In one way, I can get this to work by repeating the body and copying each result, for example:

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 think technically it’s right - you recycle each value and only insert what you know in order to be true.

?

+2

Source: https://habr.com/ru/post/1664013/


All Articles