【发布时间】:2022-01-06 13:48:39
【问题描述】:
给定一个类型,我如何编写一个递归映射类型,它产生一个具有所有相同键但它们的类型是字符串而不是它们的传入类型的类型?具体来说,我想处理嵌套对象和数组。
type MySourceType = {
field1 :string,
field2: number,
field3: number[],
field4: Date,
field5: {
nestedField1: number,
nestedField2: number[]
nestedField3: Date,
}
}
type MyDestinationType = MakeAllFieldsString<MySourceType>;
应该让步:
type MyDestinationType = {
field1 :string,
field2: string,
field3: string[],
field4: string,
field5: {
nestedField1: string,
nestedField2: string[]
nestedField3: string,
}
}
这适用于常规的“平面”对象,但无法处理嵌套对象和数组
type JsonObject<T> = {[Key in keyof T]: string; }
我也试过这个,但它似乎也没有达到我的预期。
type NestedJsonObject<T> = {
[Key in keyof T]: typeof T[Key] extends object ? JsonObject<T[Key]> : string;
}
【问题讨论】:
-
第二次尝试中“
typeof”在做什么?那里没有错误吗?如果您只是删除typeof,它会开始工作吗? -
好收获;我正在尝试不同的变化,这确实是一个错误。但是,如果没有 typeof,它就无法按预期工作......或者至少没有达到我希望的效果
-
您能否edit 您的问题不包括语法错误,以便您的示例成为minimal reproducible example?另外,由于
Date是您想要成为string的对象类型,但{a: number}是您不想 想要成为string的对象类型,您能解释一下您是如何做到的吗?希望映射能够区分您想要递归到的对象类型与不想递归的对象类型之间的区别?比如,我们可以特例Date,但这是唯一的吗?
标签: typescript typescript-typings typescript-generics