[英]Typescript change property type recursively
How to change property type recursively, im only able to do it in single dimension, judging from utility-types it seem to possible to achive that, i have tried coupe of times but can't get it right如何递归地更改属性类型,我只能在单维中进行,从实用程序类型来看似乎可以实现这一点,我已经尝试了很多次,但无法正确
type Convert<V, O extends object> = {
[Key in keyof O] : V
}
// single
{
let original = {
data1 : 1,
data2 : 1,
};
let converted : Convert<string, typeof original> = {
data1: 'a',
data2: 'a',
};
}
// recursive
{
let original = {
data1 : 1,
data2 : 1,
data3 : {
data1 : 1,
data2 : 1,
}
};
let converted : Convert<string, typeof original> = {
data1: 'a',
data2: 'a',
data3 : {
data1 : 'a',
data2 : 'a',
}
};
}
I'm pretty sure you want a recursive conditional type where you only recurse down into properties which are themselves objects:我很确定你想要一个递归条件类型,你只递归到本身就是对象的属性:
type Convert<V, O extends object> = {
[K in keyof O]: O[K] extends object ? Convert<V, O[K]> : V
}
This will cause your example code to succeed, but there may be edge cases surrounding non-primitive properties you don't want to recurse into (eg, arrays?), so you should test it thoroughly.这将导致您的示例代码成功,但可能存在围绕您不想递归进入的非原始属性的边缘情况(例如,数组?),因此您应该对其进行彻底测试。
Hope that helps;希望有所帮助; good luck!
祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.