lundi 24 mai 2021

How can I check for an expected type of a field in a type in TypeScript?

How can I check for an expected type of a field in a type in TypeScript?

E.g. I have the

class Foo {
    myField: number | undefined;
}

const a : any = { myField: "2" };

const func = (b: Foo) => {
    //here I want to check if Foo.myField is a number
    //and if it is a number, then I will run the code:
    //b.myField = +b.myField
    //I hope to find something along the same lines as:
    //if(Foo.myField is number) {}
    return JSON.stringify(b);
}

console.log(func(a));

I want to check if the b.myField is supposed to be a number and cast it to a number before stringifying it.

In real world I have that problem, because I can not change the code which generates the a, but I have a lot of fields which are stringified as strings, while actually they should be numbers. So, I do not want to type manually for each field something like this:

if(b.myField) {
    b.myField = +b.myField;
}

So, I want to somehow be able to find out that the Foo.myField is a number.

And my ultimate goal (to avoid the x-y problem) is to have the {"myField":2} as an output from the console.log instead of the {"myField":"2"}.





Aucun commentaire:

Enregistrer un commentaire