Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Typings with ForOf Values beign unknown

I started by taking a look at this question. But this was using their own typing. I am doing a forof object.entries. I have a set of values like below, I have found that I have to check the instance of to access functions on that type of object. Which make sense for all but string. I have to use String for instanceof string but then I get errors because String isn’t assignable to string. So I am lost on what to do, or if there is a better way to do this.

    const value = 
    {
        EnableDataMining: 1, EnableReassembly: 0, Alarm: [1,2,3],
        AllowQuery: 1, AllowDrilldown: 1, MessageType: ["sms", "msm","carrier pidgeon"],
        AllowBypass: 0, Bybass: (1) [false, "01/01/1970"]
    }

    for(const [k, v] of Object.entries(value))
    {
        th.headers = td.headers = th.textContent = key;
                    
        if(v instanceof Array) v.map(i => td.textContent = i);
        if(v instanceof Number) td.textContent = v.toString();
        if(v instanceof String) td.textContent = v;

        console.log(k, v);
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The correct way to check if v is a string (or a number) is to use typeof:

if (typeof v === "number") td.textContent = v.toString();
if (typeof v === "string") td.textContent = v;

Note that "string" and "number" are in quotes. typeof v gives you a string that you need to check.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading