是否有方法将传入的JSON对象映射到类型记录接口?
所以让我解释一下。我试过使用class-transformer,但它不能解决我的问题。在javascript中,我会使用object-mapper从源转换到目的地。传入对象的键可以是大写、小写、带有下划线或下划线,但是它们可以映射到相同的接口。示例
传入对象
{
'FIRST NAME': 'John',
'last_name' : 'Doe',
'Email Address': 'John.Doe@example.com'
}我想把这个映射到
{
'first_name': 'John',
'last_name': 'Doe',
'email_address': 'John.Doe@example.com'
}class-transformer的问题是,我只能在Expose中使用一个名称,我可以从传入的对象映射到这个名称。
我怎么能在打字稿里解决这个问题?
发布于 2022-04-04 06:27:59
您可以使用以下TS特性来完成这一任务:
我们将使用泛型Split类型将其拆分,并按(空格)字符拆分,将其替换为_ (下划线)。在这种情况下,我们使用递归策略来完成这一任务。
我借用了Split类型的type-fest,并从它们的各种变更用例类型那里得到了我的答案。
// Taken from type-fest https://github.com/sindresorhus/type-fest/blob/main/source/split.d.ts
type Split<
S extends string,
Delimiter extends string,
> = S extends `${infer Head}${Delimiter}${infer Tail}`
? [Head, ...Split<Tail, Delimiter>]
: S extends Delimiter
? []
: [S];
type ConvertSpaceToUnderscore<Parts extends readonly any[], PreviousPart = never> =
Parts extends [`${infer FirstPart}`, ...infer RemainingParts]
? FirstPart extends undefined
? ''
: FirstPart extends ''
? ConvertSpaceToUnderscore<RemainingParts, PreviousPart>
: RemainingParts extends {length: 0} ? Lowercase<FirstPart> : `${Lowercase<FirstPart>}_${ConvertSpaceToUnderscore<RemainingParts, PreviousPart>}`
: '';
type Convert<T extends Record<string, string>> = {
[K in keyof T as
K extends string ? ConvertSpaceToUnderscore<Split<K, ' '>> : never
]: T[K]
}然后用在你的类型上
type Input = {
'FIRST NAME': 'John',
'last_name' : 'Doe',
'Email Address': 'John.Doe@example.com'
}
type Converted = Convert<Input>
// =>
{
first_name: "John";
last_name: "Doe";
email_address: "John.Doe@example.com"
}在TS游乐场上看到它的作用
您可以根据需要添加自己的拆分器来转换任何其他字符。
然后,这种类型可以作为返回值应用于对象到对象映射器实用程序的任何实现。
https://stackoverflow.com/questions/71732121
复制相似问题