Closed OmgImAlexis closed 3 years ago
I could be wrong, but I think #54 broke the expected return type definition. It made it so that Typescript thinks that camelcaseKeys
will return the exact same input it gets as the output ... which isn't the case.
const obj = { snake_case: "yuk" };
const camelized = camelcaseKeys(obj);
// Typescript thinks camelized looks like:
// { snake_case: "yuk" }
// but it actually looks like:
// { snakeCase: "yuk" }
I don't know if there's a way to camelcase keys in interfaces/types, but perhaps a library like this simply needs to return a generic Record<string, any>
or only pass on the values of the object, instead of the exact input it gets.
This might be worth looking into https://github.com/Microsoft/TypeScript/issues/12754
@OmgImAlexis Indeed! Do you see a particular solution in there? I'm admittedly pretty green when it comes to TS, so I'm having trouble deciphering some of the proposed "hacks" (considering there's no official TS idiom for augmented mapped types)
@OmgImAlexis I'm also not able to follow the suggestions in that discussion thread. Can you point me in the right direction of how those examples might apply here? It seems like @mattrothenberg's proposed solution of defining two types (one camel cased, one snake case) isn't ideal but it's better than my current workaround of casting to an unknown and then casting to my target type.
@sindresorhus do you have any thoughts on how to fix the issue introduced by https://github.com/sindresorhus/camelcase-keys/pull/54?
I don't have any good solution for this. I think we should just revert #54.
// @jmca
Here are some immediate things you can do. There are more variations, but either way with current TS (unless something new in TS was introduced that I'm not aware of), you need to cast the object to the targeted type.
const someObj = { 'foo-bar': true }
{
type CamelType = { fooBar: boolean }
const cc = camelcaseKeys<CamelType>(someObj as any)
cc.fooBar
cc['foo-bar'] // No complaint, but not typed
}
// or
{
type CamelType = { fooBar: boolean }
type CombinedCamelType = Partial<CamelType & typeof someObj>
const cc = camelcaseKeys<CombinedCamelType>(someObj)
cc.fooBar
cc['foo-bar'] // Typed!
}
// or
{
const cc = camelcaseKeys(someObj as any)
cc.justPlainProps
}
// or
const cc = '🤪'
@sindresorhus any chance this is now possible with https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html
Some good examples in the OP https://github.com/microsoft/TypeScript/pull/40336
There's a linked PR right above your comment.
Not sure how I missed that.
If anyone wants to work on this, see the previous attempt and feedback in https://github.com/sindresorhus/camelcase-keys/pull/69.
What's the recommended way to use this currently with Typescript as all the examples are broken for me in the latest vscode.
Typescript:
3.9.0-dev-20200408
VS Code:1.44.0
Camelcase-keys:6.2.2