简体   繁体   English

打字稿递归更改属性类型

[英]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!祝你好运!

Playground link to code Playground 链接到代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 typescript 中的属性值更改界面中的属性类型? - change type of property in the interface with property value in typescript? TypeScript映射函数更改属性类型 - TypeScript map function to change property type TypeScript - 更改子项中的属性类型,是否可能? - TypeScript - Change property type in child, is it possible? 在 TypeScript 中递归展开对象类型 - Unwrap Object Type recursively in TypeScript 递归更改 TypeScript 类型的属性名称,包括嵌套数组和可选属性 - Recursively changing property names of a TypeScript type, including nested arrays and optional properties TypeScript:根据需要递归标记单个命名属性 - TypeScript: Recursively mark single named property as required Typescript:object 属性的更改类型取决于属性名称 - Typescript: Change type of object property depended on the properties name Typescript 父 class 方法返回类型由子属性更改 - Typescript parent class method return type change by child property Typescript:如何创建类型的副本但更改属性类型 - Typescript: how do you create a Copy of a type but change the property typeings 如何在 Typescript 中定义递归字符串文字类型 - How to define a recursively string literal type in Typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM