javascript - 如何在骆驼到蛇案例转换功能上指定类型
问题描述
我有一个函数可以将目标字符串、数组或对象的大小写从驼峰式转换为蛇形。
convertCamelToSnake (target) {
// Complex logic to convert target depending on what type it is
return convertedTarget
}
我想使用这样的 Generic 在这个函数上指定类型:
convertCamelToSnake <T>(target: T):T {
// Complex logic to convert target depending on what type it is
return convertedTarget
}
这适用于字符串和数组,但我们将给定对象的键转换为蛇形大小写。但是打字稿没有意识到这一点,并假设键保持不变,因为我们声明我们正在返回T
。
我怎样才能保留知道返回类型的能力。即字符串、数组、对象,而让字典的键不明确?
例如,假设我们传入:
const a = { helloWorld: "bob", age: 21 }
a = convertCamelToSnake(a); // { hello_world: "bob", age: 21 };
a.hello_world; // Property 'hello_world' does not exist on type
我们如何做到这一点,以便我们可以hello_world
在转换对象后访问属性,同时仍然能够推断出返回值是类型的object
(例如,因为我们也可以将数组传递给这个函数)?
解决方案
推荐阅读
- typescript - Typescript 接口上的类型推断
- javascript - Context.provider 用它包装我的应用程序组件时抛出错误
- rust - 使用 Rust 宏简化“匹配”
- java - 使用firebase时如何检查特定文档中是否存在字段?
- css - 文本没有换行到下一行 - 特别是在 IE 中
- javascript - 为什么 Uncaught TypeError: Cannot set property 'innerHTML' of null 显示即使 id 在和 js 中相同?
- python - 无法保存包含 DNNRegressor 估计器的 tensorflow 模型
- php - 使用 php/laravel 使 XML 模板动态化
- swift - JSON 与 SwiftUI 使用数组
- c# - 在不知道其类型 EF 的情况下查找具有唯一 ID 的实体