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;
};
}
T[key]['value' & keyof T[key]]