Search code examples
javascripttypescriptkeyof

Typescript: access nested object values through keys defined in array


I was wondering how I could make the error on this LINK disappear.

tl;dr I have a type that has both nested properties(object) and regular ones(string,boolean etc.). I am trying to check if nested values are non empty strings. But considering there are many of them I am using a string array with the type keys that should be checked. I am looking for a solution that will not force me to split the defined type into separate types and then just merging them together.

Thanks in advance

EDIT: ADDED CODE AND UPDATED TYPESCRIPT PLAYGROUND LINK

type MyRecord={
    id:string;
    value:string;
}
type MyType={
    a:MyRecord;
    b:MyRecord;
    c:string,
    d:string,
}

const validate = (r:MyType)=>{
    const keys=["a","b"];
    for (const key of keys){
        if(r[key as keyof MyType].value!==""){
           return false
        }
    }
    return true
}

Thrown error:

Property 'value' does not exist on type 'string | MyRecord'. Did you mean 'valueOf'?
  Property 'value' does not exist on type 'string'.

Solution

  • Instead of having keys as a string[] you could add a as const to make the type readonly ["a", "b"]

    const validate = (r:MyType)=>{
        const keys=["a","b"] as const;
        for (const key of keys){
            if(r[key].value!==""){
    
            }
        }
        return true
    }