Skip to content

Can't return Results on Tanstack Start server functions #62

@Joseevb

Description

@Joseevb

When creating a Tanstack Start server function

class TestError extends TaggedError('TestError')<{ message: string }>() {}

const testServerFn = createServerFn().handler(() => {
  const random = Math.random()

  let result

  if (random < 0.5) {
    result = Result.ok('Success!')
  } else {
    result = Result.err(new TestError({ message: 'Something went wrong!' }))
  }

  return Result.serialize(result)
})

TypeScript gives the following error:

Argument of type '() => SerializedResult<string, TestError>' is not assignable to parameter of type 'ServerFn<Register, Method, undefined, undefined, SerializedResult<string, TestError>>'.
Type 'SerializedResult<string, TestError>' is not assignable to type 'ValidateSerializableMapped<SerializedOk, RegisteredSerializableInput> | ValidateSerializableMapped<...>'.
Type 'SerializedErr' is not assignable to type 'ValidateSerializableMapped<SerializedOk, RegisteredSerializableInput> | ValidateSerializableMapped<...>'.
Type 'SerializedErr' is not assignable to type 'ValidateSerializableMapped<SerializedErr, RegisteredSerializableInput>'.
The types of 'error.cause' are incompatible between these types.
Type 'unknown' is not assignable to type 'SerializationError<"Type may not be serializable"> | undefined'.

Without the Result.serialize()

class TestError extends TaggedError('TestError')<{ message: string }>() {}

const testServerFn = createServerFn().handler(() => {
  const random = Math.random()

  let result

  if (random < 0.5) {
    result = Result.ok('Success!')
  } else {
    result = Result.err(new TestError({ message: 'Something went wrong!' }))
  }

  return result
})

Argument of type '() => SerializedResult<string, TestError>' is not assignable to parameter of type 'ServerFn<Register, Method, undefined, undefined, SerializedResult<string, TestError>>'.
Type 'SerializedResult<string, TestError>' is not assignable to type 'ValidateSerializableMapped<SerializedOk, RegisteredSerializableInput> | ValidateSerializableMapped<...>'.
Type 'SerializedErr' is not assignable to type 'ValidateSerializableMapped<SerializedOk, RegisteredSerializableInput> | ValidateSerializableMapped<...>'.
Type 'SerializedErr' is not assignable to type 'ValidateSerializableMapped<SerializedErr, RegisteredSerializableInput>'.
The types of 'error.cause' are incompatible between these types.
Type 'unknown' is not assignable to type 'SerializationError<"Type may not be serializable"> | undefined'.

This makes it impossible to return the plain Result object on the server functions and handle them on the client/caller. How could this be solved?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions