gpt4 book ai didi

typescript - 如何使用不同的键名来干燥两个相似的 typescript 界面

转载 作者:行者123 更新时间:2023-12-05 09:26:43 27 4
gpt4 key购买 nike

我有两种不同格式的相同界面,一种是键由低破折号分隔的 JSON 格式,另一种是 javascript camelCase 格式:

JSON 格式:

interface MyJsonInterface {
key_one: string;
key_two: number;
}

interface MyInterface {
keyOne: string;
keyTwo: number;
}

我想防止重复,但不知道正确的方法。我查看了this question但答案并不令人满意,因为我不希望两个界面都使用相同的键。

还有其他方法吗?

最佳答案

让我们将此任务拆分为更小的子任务。首先,您需要编写一个实用程序类型,将 snake_case 转换为 camelCase。让我们专注于它。

看这个:

type Separator = '_'
type Convert<Str extends string, Acc extends string = ''> =
// Check if Str mathes the pattern string_string
(Str extends `${infer Head}${Separator}${infer Tail}`
// If yes, check whether it is a first call or not, because we don't want to capitalize for part of the string
? (Acc extends ''
// This is a first call, because Acc is empty, hence first part should not be capitalized
? Convert<Tail, `${Acc}${Head}`>
// This is not first call, hence Head should be capitalized
: Convert<Tail, `${Acc}${Capitalize<Head>}`>)
// This is the last call, because Str does not match the pattern
: `${Acc}${Capitalize<Str>}`)

现在,我们可以遍历界面并将每个键替换为转换后的键:

type Builder<T> = {
[Prop in keyof T as Convert<Prop & string>]: T[Prop]
}

// {
// oneTwoThreeFourthFiveSixSevenEightNineTen: "hello";
// }
type Result = Builder<{
one_two_three_fourth_five_six_seven_eight_nine_ten: 'hello'
}>

Playground完整代码

反之亦然:

type Separator = '_'

type IsChar<Char extends string> = Uppercase<Char> extends Lowercase<Char> ? false : true;

type IsCapitalized<Char extends string> =
IsChar<Char> extends true
? Uppercase<Char> extends Char
? true
: false
: false

type Replace<Char extends string> =
IsCapitalized<Char> extends true
? `${Separator}${Lowercase<Char>}`
: Char

type Result2 = Replace<'A'>

type CamelToSnake<
Str extends string,
Acc extends string = ''
> =
Str extends `${infer Char}${infer Rest}` ? CamelToSnake<Rest, `${Acc}${Replace<Char>}`> : Acc

// type Result = "foo_bar_baz"
type Result = CamelToSnake<'fooBarBaz'>

Playground

关于typescript - 如何使用不同的键名来干燥两个相似的 typescript 界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73432506/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com