Recursive conditional types

后端 未结 3 870
走了就别回头了
走了就别回头了 2021-01-22 04:22

I\'d like to map an object recursively so that the primitive values in the object are converted to some other type.

For example, I\'d like an object like this:

3条回答
  •  无人共我
    2021-01-22 05:13

    You were really close. The problem here is that string is assignable to {}.

    Demonstration of this fact here.

    If you check for the string, number, etc. first before {}, then you can get what you want:

    type ConvertToTest = {
        [P in keyof T]: T[P] extends any[]
            ? ConvertToTest
            : T[P] extends string
            ? Test
            : T[P] extends number
            ? Test
            : T[P] extends boolean
            ? Test
            : ConvertToTest
    }
    

提交回复
热议问题