Answer the question
In order to leave comments, you need to log in
How to convert the required values to the desired type in typescript?
We have an options object
{
param1: "1",
param2: "string",
param3: "false"
}
export class PageParams {
param1: number;
param2: string;
param3: boolean;
}
Answer the question
In order to leave comments, you need to log in
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}
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question