Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

serverOnly return type should consider parameters of the passed function #2828

Open
revosw opened this issue Nov 22, 2024 · 0 comments
Open

Comments

@revosw
Copy link

revosw commented Nov 22, 2024

Which project does this relate to?

Start

Describe the bug

serverOnly does not return the correct type.

As of v1.82.4, serverOnly is declared like this.

export declare function serverOnly<T>(value: () => T): () => T | undefined;

This means that when I have a serverOnly function like this:

import { serverOnly } from "@tanstack/start";

export const getPokemon = serverOnly(async (pokemon: string) => {
  return await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`).then(res => res.json());
});

getPokemon is inferred to have the type () => Promise<any> | undefined, which means passing the pokemon parameter leads to a typescript error

export const Route = createRootRoute({
  beforeLoad: async () => {
    const pokemon = await getPokemon("ditto");
                                     // ^ Expected 0 arguments, but got 1. (2554)
    return {pokemon}
  },
  component: RootComponent,
});

Alternative method

You can wrap the anonymous function inside another anonymous function to get the correct return type

import { serverOnly } from "@tanstack/start";

// Notice () => async () => {}
export const getPokemon = serverOnly(() => async (pokemon: string) => {
  return await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon}`).then(res => res.json());
});

But you will have to "unwrap" once

export const Route = createRootRoute({
  beforeLoad: async () => {
    const pokemon = await getPokemon?.()("ditto");
    return { pokemon };
  },
  component: RootComponent,
});

Your Example Website or App

https://stackblitz.com/edit/github-avg9mj-9r1rad?file=app%2Froutes%2F__root.tsx

Steps to Reproduce the Bug or Issue

  1. Go to __root.tsx
  2. Observe that I can't pass "ditto" as an argument to getPokemon, even if the function passed to serverOnly has a parameter of type string

Expected behavior

getPokemon should be inferred as (pokemon: string) => Promise<any> | undefined

Screenshots or Videos

No response

Platform

  • OS: Windows
  • Browser: Microsoft Edge
  • Version: Version 131.0.2903.51 (Official build) (64-bit)

Additional context

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant