You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何指定函数返回对象的所有值均为小写格式?

TypeScript 限定返回对象所有值为小写的实现方法

你当前的实现运行时功能是正常的,但存在缺陷:类型层面没有体现返回值已经全部转为小写的特性,无法在编译阶段获得对应的类型提示和校验。我们可以结合TS内置的Lowercase工具类型和映射类型优化实现,同时满足运行时功能和类型约束的要求。

优化后实现代码

// 定义返回值类型:遍历原对象所有键,将对应值的类型转为小写版本
type LowercaseObjectValues<T extends Record<keyof T, string>> = {
  [K in keyof T]: Lowercase<T[K]>
}

const lowercaseObjValues = <T extends Record<keyof T, string>>(
  obj: T
): LowercaseObjectValues<T> => {
  return Object.keys(obj).reduce((acc, key: keyof T) => {
    acc[key] = obj[key].toLowerCase() as Lowercase<T[typeof key]>
    return acc
  }, {} as LowercaseObjectValues<T>)
}

效果验证

const testObj = {
  name: "JOHN DOE",
  email: "EXAMPLE@DOMAIN.COM",
  address: "123 MAIN ST"
}

const result = lowercaseObjValues(testObj)
// 此时result的类型会被自动推导为:
// {
//   name: "john doe",
//   email: "example@domain.com",
//   address: "123 main st"
// }

注意事项

  • 该实现依赖TypeScript 4.1及以上版本提供的内置Lowercase工具类型,低版本TS环境需要先升级版本
  • 如果原对象的值是通用string类型而非字符串字面量类型,返回值的类型会推导为string,属于正常情况,因为Lowercase<string>本身就是string类型

内容的提问来源于stack exchange,提问作者Aigars Peda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:45:01