Skip to content
Source
Sign inSign up
TanStack/virtual

fix(virtual-core): add TKey generic to allow key type narrowing #1140

OpenrestareaByWeezy(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/1140/headopened

Changes

VirtualItem.key is typed as Key = number | string | bigint, but React's Key type only accepts string | number. This causes a TypeScript error when passing virtualItem.key directly to a component's key prop:

Type 'bigint' is not assignable to type 'Key | null | undefined'

This adds a TKey extends Key = Key generic parameter to VirtualItem, VirtualizerOptions, and the Virtualizer class, threaded through all framework adapters (React, Vue, Solid, Svelte, Angular, Lit). The default keeps the change fully backward-compatible — no existing code needs to change.

const virtualizer = useVirtualizer<HTMLDivElement, HTMLDivElement, number>({
  count: items.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 35,
})

virtualizer.getVirtualItems().map((item) => (
  <div key={item.key}>...</div> // no type error
))

Closes #971

Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).
    1. changeset-bot[bot](GitHub profile, opens in a new tab)commented

      🦋 Changeset detected

      Latest commit: ff2110487cb3810905576209a561e6ab6336b335

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 7 packages
      NameType
      @tanstack/virtual-coreMinor
      @tanstack/react-virtualMinor
      @tanstack/vue-virtualMinor
      @tanstack/solid-virtualMinor
      @tanstack/svelte-virtualMinor
      @tanstack/angular-virtualMinor
      @tanstack/lit-virtualMinor

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

    2. Pull request overview

      This PR introduces a TKey generic across @tanstack/virtual-core and all framework adapters so consumers can narrow VirtualItem.key (eg to number) and avoid React key prop type errors caused by bigint being part of the default Key union.

      Changes:

      • Export Key from virtual-core and add TKey extends Key = Key to VirtualItem, VirtualizerOptions, and Virtualizer.
      • Thread TKey through React/Vue/Solid/Svelte/Angular/Lit adapter APIs so useVirtualizer/controllers can expose narrowed virtualItem.key.
      • Add a changeset bumping all affected packages.

      Reviewed changes

      Copilot reviewed 10 out of 10 changed files in this pull request and generated 3 comments.

      Show a summary per file
      FileDescription
      packages/virtual-core/src/index.tsAdds exported Key type and TKey generics to core types/classes.
      packages/react-virtual/src/index.tsxThreads TKey through React adapter option/type signatures.
      packages/vue-virtual/src/index.tsThreads TKey through Vue composables.
      packages/solid-virtual/src/index.tsxThreads TKey through Solid adapter helpers.
      packages/svelte-virtual/src/index.tsThreads TKey through Svelte adapter store wrapper.
      packages/angular-virtual/src/types.tsUpdates Angular virtualizer wrapper types to include TKey.
      packages/angular-virtual/src/proxy.tsUpdates proxy typing/inference to propagate key type.
      packages/angular-virtual/src/index.tsThreads TKey through Angular injection APIs.
      packages/lit-virtual/src/index.tsThreads TKey through Lit controllers.
      .changeset/add-tkey-generic-parameter.mdChangeset for patch releases across packages.

      💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

      @@ -305,5 +306,5 @@
      305306 scrollToFn: (
      306307 offset: number,
      307308 options: { adjustments?: number; behavior?: ScrollBehavior },
      308- instance: Virtualizer<TScrollElement, TItemElement>,
      309+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      309310 ) => void

      VirtualizerOptions now types the instance parameter for scrollToFn (and similarly the other adapter callbacks) as Virtualizer<..., any>. That erases the new TKey type and prevents virtualizer.getVirtualItems() from being strongly typed inside these callbacks when users override them. Use Virtualizer<TScrollElement, TItemElement, TKey> for the instance parameter (or introduce a minimal instance interface if this was done to break a recursive type).

      piecykcommented

      Yeah, here adapter-level callbacks (scrollToFn, observeElementRect, observeElementOffset) intentionally remain any, they're framework plumbing that never exposes TKey to end users, and keeping them loose avoids forcing framework adapters to thread TKey through their standalone functions.

      @@ -308,17 +309,17 @@
      308- instance: Virtualizer<TScrollElement, TItemElement>,
      309+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      309310 ) => void
      310311 observeElementRect: (
      311- instance: Virtualizer<TScrollElement, TItemElement>,
      312+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      312313 cb: (rect: Rect) => void,
      313314 ) => void | (() => void)
      314315 observeElementOffset: (
      315- instance: Virtualizer<TScrollElement, TItemElement>,
      316+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      316317 cb: ObserveOffsetCallBack,
      317318 ) => void | (() => void)
      318319 // Optional
      319320 debug?: boolean
      320321 initialRect?: Rect
      321322 onChange?: (
      322- instance: Virtualizer<TScrollElement, TItemElement>,
      323+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      323324 sync: boolean,
      324325 ) => void

      onChange is typed with instance: Virtualizer<..., any>, which causes consumers to lose the TKey narrowing inside onChange (eg instance.getVirtualItems() becomes VirtualItem<any>[]). If the goal is to let users narrow VirtualItem.key, this callback should receive Virtualizer<TScrollElement, TItemElement, TKey> so the key type is preserved.

      @@ -448,4 +450,4 @@
      448450 scrollPaddingStart: 0,
      449451 scrollPaddingEnd: 0,
      450452 horizontal: false,
      451- getItemKey: defaultKeyExtractor,
      453+ getItemKey: defaultKeyExtractor as (index: number) => TKey,

      defaultKeyExtractor returns a number, but it's being asserted to (index: number) => TKey. If a caller explicitly sets TKey to a type that does not include number (eg string or bigint) and omits getItemKey, the typings will claim VirtualItem.key is TKey while runtime keys are still numeric indices. Consider making getItemKey required unless number extends TKey, or otherwise avoid typing the default extractor as returning TKey when it can only return number.

      Suggested change
      453- getItemKey: defaultKeyExtractor as (index: number) => TKey,
      453+ getItemKey: defaultKeyExtractor,
      piecykcommented

      Yes, this is a real type hole. Casting defaultKeyExtractor to (index: number) => TKey is only safe if the public API makes it impossible to instantiate TKey as a non-number type without also providing getItemKey. Otherwise typings can claim VirtualItem.key is string/bigint while runtime still returns numeric indices.

      Maybe something like?

      // Enforces that getItemKey is required when TKey excludes number.
      type VirtualizerInputOptions<
        TScrollElement extends Element | Window,
        TItemElement extends Element,
        TKey extends Key = Key,
      > = number extends TKey
        ? VirtualizerOptions<TScrollElement, TItemElement, TKey>
        : Omit<VirtualizerOptions<TScrollElement, TItemElement, TKey>, 'getItemKey'> &
            { getItemKey: (index: number) => TKey }
    3. piecyk requested changes

      Thanks for the contribution, overall the direction makes sense and narrowing the key type is useful (especially for React where bigint in the default Key union causes issues with virtualItem.key).

      However, I think there are a couple of things we should address before merging:

      • Unsound typing of the default getItemKey - this one is a bit tricky. defaultKeyExtractor always returns a number, but it's currently asserted to (index: number) => TKey. That means a consumer could instantiate TKey as something that does not include number (e.g. string) while omitting getItemKey, and the types would claim VirtualItem.key is TKey while runtime keys are still numeric indices.

      • any leaking in callbacks - onChange, measureElement, etc. currently use Virtualizer<..., any>

      • Release type – this adds a new generic parameter to several public types (VirtualItem, VirtualizerOptions, Virtualizer) across core and adapters, so this should likely be a minor release rather than patch.

      @@ -0,0 +1,8 @@
      1+---
      2+'@tanstack/virtual-core': patch
      3+'@tanstack/react-virtual': patch
      4+'@tanstack/vue-virtual': patch
      5+'@tanstack/solid-virtual': patch
      6+'@tanstack/svelte-virtual': patch
      7+'@tanstack/angular-virtual': patch
      8+'@tanstack/lit-virtual': patch
      piecykcommented
      Suggested change
      2-'@tanstack/virtual-core': patch
      3-'@tanstack/react-virtual': patch
      4-'@tanstack/vue-virtual': patch
      5-'@tanstack/solid-virtual': patch
      6-'@tanstack/svelte-virtual': patch
      7-'@tanstack/angular-virtual': patch
      8-'@tanstack/lit-virtual': patch
      2+'@tanstack/virtual-core': minor
      3+'@tanstack/react-virtual': minor
      4+'@tanstack/vue-virtual': minor
      5+'@tanstack/solid-virtual': minor
      6+'@tanstack/svelte-virtual': minor
      7+'@tanstack/angular-virtual': minor
      8+'@tanstack/lit-virtual': minor

      I don’t think this should be a patch release. It adds a new generic parameter to the public API across core and adapters, which is a type-surface change and potentially affects inference/compatibility for consumers. This feels more like a minor than a patch.

      @@ -306,17 +307,17 @@
      306307 offset: number,
      307308 options: { adjustments?: number; behavior?: ScrollBehavior },
      308- instance: Virtualizer<TScrollElement, TItemElement>,
      309+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      309310 ) => void
      310311 observeElementRect: (
      311- instance: Virtualizer<TScrollElement, TItemElement>,
      312+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      312313 cb: (rect: Rect) => void,
      313314 ) => void | (() => void)
      314315 observeElementOffset: (
      315- instance: Virtualizer<TScrollElement, TItemElement>,
      316+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      316317 cb: ObserveOffsetCallBack,
      317318 ) => void | (() => void)
      318319 // Optional
      319320 debug?: boolean
      320321 initialRect?: Rect
      321322 onChange?: (
      322- instance: Virtualizer<TScrollElement, TItemElement>,
      323+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      piecykcommented
      Suggested change
      323- instance: Virtualizer<TScrollElement, TItemElement, any>,
      323+ instance: Virtualizer<TScrollElement, TItemElement, TKey>,

      Let's use here TKey (not any) so that consumers retain full key-type narrowing inside the callback.

      @@ -312,17 +312,18 @@
      312+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      312313 cb: (rect: Rect) => void,
      313314 ) => void | (() => void)
      314315 observeElementOffset: (
      315- instance: Virtualizer<TScrollElement, TItemElement>,
      316+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      316317 cb: ObserveOffsetCallBack,
      317318 ) => void | (() => void)
      318319 // Optional
      319320 debug?: boolean
      320321 initialRect?: Rect
      321322 onChange?: (
      322- instance: Virtualizer<TScrollElement, TItemElement>,
      323+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      323324 sync: boolean,
      324325 ) => void
      325326 measureElement?: (
      326327 element: TItemElement,
      327328 entry: ResizeObserverEntry | undefined,
      328- instance: Virtualizer<TScrollElement, TItemElement>,
      329+ instance: Virtualizer<TScrollElement, TItemElement, any>,
      piecykcommented
      Suggested change
      329- instance: Virtualizer<TScrollElement, TItemElement, any>,
      329+ instance: Virtualizer<TScrollElement, TItemElement, TKey>,

      Same as onChange

      piecykreplied on packages/virtual-core/src/index.ts lines 306 to 310

      Yeah, here adapter-level callbacks (scrollToFn, observeElementRect, observeElementOffset) intentionally remain any, they're framework plumbing that never exposes TKey to end users, and keeping them loose avoids forcing framework adapters to thread TKey through their standalone functions.

      @@ -448,7 +450,7 @@
      448450 scrollPaddingStart: 0,
      449451 scrollPaddingEnd: 0,
      450452 horizontal: false,
      451- getItemKey: defaultKeyExtractor,
      453+ getItemKey: defaultKeyExtractor as (index: number) => TKey,
      452454 rangeExtractor: defaultRangeExtractor,
      453455 onChange: () => {},
      454456 measureElement,
      piecykcommented

      The as any is needed because of a type mismatch between the standalone measureElement function and what VirtualizerOptions now expects.

      Having

      Suggested change
      456- measureElement,
      456+ measureElement: measureElement as any?,

      Alternatively, you could avoid as any by updating the standalone function's signature to also be generic over TKey

      piecykreplied on packages/virtual-core/src/index.ts line 453

      Yes, this is a real type hole. Casting defaultKeyExtractor to (index: number) => TKey is only safe if the public API makes it impossible to instantiate TKey as a non-number type without also providing getItemKey. Otherwise typings can claim VirtualItem.key is string/bigint while runtime still returns numeric indices.

      Maybe something like?

      // Enforces that getItemKey is required when TKey excludes number.
      type VirtualizerInputOptions<
        TScrollElement extends Element | Window,
        TItemElement extends Element,
        TKey extends Key = Key,
      > = number extends TKey
        ? VirtualizerOptions<TScrollElement, TItemElement, TKey>
        : Omit<VirtualizerOptions<TScrollElement, TItemElement, TKey>, 'getItemKey'> &
            { getItemKey: (index: number) => TKey }
    4. restareaByWeezy(GitHub profile, opens in a new tab)commented

      Thanks for the detailed feedback, really helpful. @piecyk

      Here's what's been updated:

      Changeset: Bumped to minor across all packages. Agreed — adding a generic parameter to the public type surface warrants a minor, not a patch.

      onChange and measureElement callbacks: Both now receive Virtualizer<TScrollElement, TItemElement, TKey> for the instance parameter, so key-type narrowing is preserved inside those callbacks.

      scrollToFn / observeElementRect / observeElementOffset: Left as any per the suggestion — these are framework plumbing and don't need to expose TKey.

      VirtualizerInputOptions: Added the conditional type as proposed. getItemKey is now required when number extends TKey evaluates to false, which closes the type hole with defaultKeyExtractor.

      Standalone measureElement signature: Updated the function to accept Virtualizer<any, TItemElement, any>, which removes the need for the as any cast in setOptions.


      One thing I noticed while going through this: the as VirtualizerInputOptions assertion inside each adapter's internal createVirtualizerBase means the getItemKey enforcement only applies when instantiating Virtualizer directly. Framework adapter users specifying TKey = string without getItemKey would still not get a type error, since the public-facing hooks (useVirtualizer, createVirtualizer, etc.) all accept VirtualizerOptions where getItemKey remains optional.

      I went ahead and updated the public option types in all adapters to include the same conditional requirement, so the enforcement is consistent regardless of how the virtualizer is instantiated. Let me know if you'd prefer to split that out into a separate PR — happy to do either way.

    5. piecyk requested changes

      @@ -348,3 +349,12 @@
      348349 useAnimationFrameWithResizeObserver?: boolean
      349350 }
      350351
      352+export type VirtualizerInputOptions<
      353+ TScrollElement extends Element | Window,
      354+ TItemElement extends Element,
      355+ TKey extends Key = Key,
      356+> = number extends TKey
      357+ ? VirtualizerOptions<TScrollElement, TItemElement, TKey>
      358+ : Omit<VirtualizerOptions<TScrollElement, TItemElement, TKey>, 'getItemKey'> & {
      359+ getItemKey: (index: number) => TKey
      360+ }
      piecykcommented

      Now while reading this, i’m leaning towards flattening it.

      The conditional type protects a pretty unlikely edge case (someone explicitly sets TKey = string but forgets getItemKey), but in practice it seems to hurt adapter inference more than it helps. Since none of the adapters or examples actually exercise that path, the added complexity in the core type probably isn’t worth it.

      In the worst case a user would get numeric keys at runtime while declaring string, which should be pretty obvious and easy to fix by providing getItemKey.

      So simplifying the type and dropping the conditional sounds reasonable to me 👍

      restareaByWeezy(GitHub profile, opens in a new tab)commented

      @piecyk Agreed, dropped the conditional type entirely. Constructor goes back to plain VirtualizerOptions and all the as VirtualizerInputOptions casts in adapters are gone too. Much cleaner this way.

Sign in to join this conversation.