Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/deep-value-optional-key.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/table-core': patch
---

Preserve `undefined` in `DeepValue` accessor value types when a deep string accessor key traverses an optional or nullable parent key. `getValue()` for a path like `user.salary.amount` is now typed as `number | undefined` when `salary` is optional, matching the optional-chaining behavior of the runtime deep accessor.
5 changes: 3 additions & 2 deletions packages/table-core/src/types/type-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ type DeepKeysPrefix<
? `${TPrefix}.${DeepKeys<T[TPrefix], [...TDepth, any]> & string}`
: never

export type DeepValue<T, TProp> =
T extends Record<string | number, any>
export type DeepValue<T, TProp> = T extends null | undefined
? undefined
: T extends Record<string | number, any>
? TProp extends `${infer TBranch}.${infer TDeepProp}`
? DeepValue<T[TBranch], TDeepProp>
: T[TProp & keyof T]
Expand Down
29 changes: 29 additions & 0 deletions packages/table-core/tests/unit/helpers/columnHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,33 @@ describe('createColumnHelper', () => {
expect(row.getValue('0')).toBe('Alice')
expect(row.getValue('1')).toBe(42)
})

it('should preserve undefined for optional deep accessor keys', () => {
type DeepPerson = {
user: {
salary?: {
amount: number
}
}
}
const deepHelper = createColumnHelper<typeof features, DeepPerson>()
const column = deepHelper.accessor('user.salary.amount', {
cell: (info) => {
// `salary` is optional, so the resolved deep value can be `undefined`
expectTypeOf(info.getValue()).toEqualTypeOf<number | undefined>()
return info.getValue()
},
})
const table = constructTable<typeof features, DeepPerson>({
features,
columns: deepHelper.columns([column]),
data: [{ user: { salary: { amount: 42 } } }],
})
const row = table.getRowModel().rows[0]!

expect(table.getAllLeafColumns().map((c) => c.id)).toEqual([
'user_salary_amount',
])
expect(row.getValue('user_salary_amount')).toBe(42)
})
})