roivasot
roivasot

Reputation: 65

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'.

Upvotes: 0

Views: 1010

Answers (2)

rycha
rycha

Reputation: 804

I had this problem. And found only one way to resolve this

type MyRecord = {
    id:string;
    value:string;
} & string

type StrObj = {
    a: MyRecord,
    b: MyRecord,
    c: MyRecord,
    d: MyRecord,
}

type A = keyof StrObj


const validate = (r:StrObj)=>{
    const keys: Array<A> = ["a" ,"b"]
    for (const key of keys) {
        if (r[key].value) {

        }
    }
    return true
}

In my opinion looks like not the best way... But works. Recently I tried to find other solution, but looks like there is no other solution

Upvotes: 2

thedude
thedude

Reputation: 9822

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
}

Upvotes: 0

Related Questions