F
F
flafy42020-02-13 10:59:23
JavaScript
flafy4, 2020-02-13 10:59:23

How to convert the required values ​​to the desired type in typescript?

We have an options object

{
param1: "1",
param2: "string",
param3: "false"
}


Now all the values ​​we have are of type string, but we know that param1 must be number, param2 - string, param3 - boolean.
There is also a class that describes these properties:

export class PageParams {
    param1: number;
    param2: string;
    param3: boolean;
}


How can I correctly describe a function that will convert all values ​​in an object to the types that are described in the class?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Yarkov, 2020-02-13
@flafy4

If I understood the problem correctly, then something like this:

const obj = {
  param1: "1",
  param2: "string",
  param3: "false"
};

function convertType(prop) {
  try {
    return JSON.parse(prop);
  } catch (e) {
    if (e.name === 'SyntaxError') {
      return prop;
    }
    throw e;
  }
}

Object.entries(obj).forEach(([key, value]) => {
  obj[key] = convertType(value);
});

console.log(obj); // {param1: 1, param2: "string", param3: false}

A
abberati, 2020-02-13
@abberati

There are no static types in runtime, therefore, to implement such a cast is not to send two bytes. If you want a reliable solution, look towards runtypes , this balalaika is capable of such transformations. But there, not from the ts-annotation of the type/interface/class, the cast types are calculated, but vice versa.

A
Anton Shvets, 2020-02-13
@Xuxicheta

https://learn.javascript.ru/types-conversion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question