0

I have a deeply nested object structure that contains other objects that all should have a value key, I'm trying to keep the object structure and replace the values with the type of values for each key. Now I've created a type Result that almost does what I need it to do, however, the created type also has an error.

T[key]['value'] - Type '"value"' cannot be used to index type 'T[key]'.(2536)

I'm also struggling with how to do it that if the value prop does not exist, it defaults to string

class A<T = string>{
    constructor(public value:T){}
}

const data = {
    propA: {value:'test'},
    nested:{
        propA: new A([123]),
        propBool: new A(123)
    }
}


type Replace<T, A extends {value:any}={value:any}> = T extends object
    ? { [key in keyof T]: T[key] extends {value:any}? T[key]['value'] : Replace<T[key], A> }
    : T;


type Result = Replace<typeof data> //ok

class A<T = string>{
    constructor(public value:T){}
}

const data = {
    propA: {value:'test'},
    nested:{
        propA: new A([123]),
        propBool: new A(123)
    }
}


type Replace<T, A extends {value:any}={value:any}> = T extends object
    ? { [key in keyof T]: T[key] extends {value:any}? T[key]['value'] : Replace<T[key], A> }
    : T;


type Result = Replace<typeof data>

// result
type Result = {
    propA: string;
    nested: {
        propA: number[];
        propBool: number;
    };
}

Typescript Playground

2
  • This looks exactly the same as stackoverflow.com/questions/67240685/…, so you can do the same thing - T[key]['value' & keyof T[key]] Commented Apr 24, 2021 at 13:59
  • @NadiaChibrikova Can you post this as the answer so I can accept it. Commented Apr 26, 2021 at 18:49

1 Answer 1

1

You can use an intersection type to affirm thatvalue is one of the fields of T[key]: T[key]['value' & keyof T[key]]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.