首页 > 解决方案 > 如何在骆驼到蛇案例转换功能上指定类型

问题描述

我有一个函数可以将目标字符串、数组或对象的大小写从驼峰式转换为蛇形。

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(例如,因为我们也可以将数组传递给这个函数)?

标签: javascripttypescript

解决方案


推荐阅读