kbrabrand / camelize-ts

A typescript typed camelCase function that recursively camel cases a snake cased object structure
20 stars 5 forks source link

Camelizing nested properties with a null union breaks #51

Open LordZardeck opened 1 year ago

LordZardeck commented 1 year ago

If you have a child prop that has a null union, Camelize stops trying to camelize that property. The following is a basic reproducable example:

import type { Camelize } from 'camelize-ts'
import camelize from 'camelize-ts'

type SnakeCasedChild = {
    foo_bar: string
}

type SnakeCasedParent = {
    child: SnakeCasedChild[] | null
}

type CamelCasedParent = Camelize<SnakeCasedParent>

const myObject: CamelCasedParent = camelize({
    child: [{ foo_bar: 'hello' }],
})

myObject.child?.map((child) => child.fooBar)

You'll notice that TypeScript complains that child.fooBar is not a valid property, but child.foo_bar is.

LordZardeck commented 1 year ago

I would start a PR that adds a failing test for this, but I this repository doesn't have type testing. That might be useful.

LordZardeck commented 1 year ago

Quick question, is there a reason not to just use type-fest's CamelCasedPropertiesDeep? seems redundant to have the same type. This library could just be the function to camelcase the properties at runtime. Since type-fest is a type-only library, it shouldn't have any extra build bloat.

jonkoops commented 1 year ago

I'd rather not add any dependencies to this project if we can avoid it. But we can certainly steal the implementation from type-fest if it works better (with proper attribution ofc).

Balastrong commented 1 week ago

I'm here with a model having a nullable item, asking to cover that case :D

I'm not a ts wizard so maybe I'm wrong, but I see that it works by adding | null next to {} | undefined here. Does it break anything else?

https://github.com/kbrabrand/camelize-ts/blob/16759acdc21b3cc0d62720b31378421ba461f69d/src/index.ts#L11-L14