gpt4 book ai didi

typescript 映射键到大写

转载 作者:行者123 更新时间:2023-12-05 05:05:02 30 4
gpt4 key购买 nike

我有以下对象:

const foo = {
fieldAnt: "foo",
fieldCab: "baz"
};

我想自动将其映射到一个键为大写并带有下划线的类型:

type FIELDS = {
FIELD_ANT: "fieldAnt",
FIELD_CAB: "fieldCab"
}

是否可以使用 keyof 或类型映射以编程方式使用 typescript 实现此目的?

最佳答案

有点晚了 :P 但是,有了 little help我能够做到:

const foo = {
fieldAnt: "foo",
fieldCab: "baz"
};

type CamelToSnakeCase<S extends string> =
S extends `${infer T}${infer U}` ?
`${T extends Capitalize<T> ? "_" : ""}${Lowercase<T>}${CamelToSnakeCase<U>}` :
S

type Convert<T> = { [P in keyof T as Uppercase<CamelToSnakeCase<string & P>>]: P }

type Fields = Convert<typeof foo>
// type Fields = {
// FIELD_ANT: "fieldAnt",
// FIELD_CAB: "fieldCab"
// }

TS Playground

关于 typescript 映射键到大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60762559/

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