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

[Typescript] StateValue is not typesafe #3504

Closed
mrchantey opened this issue Aug 8, 2022 · 4 comments
Closed

[Typescript] StateValue is not typesafe #3504

mrchantey opened this issue Aug 8, 2022 · 4 comments

Comments

@mrchantey
Copy link

Description

Working with machine.transition() and other implementations of StateValue, the type is not provided. The type safety is provided elsewhere, ie state.matches:

TSV extends TResolvedTypesMeta extends TypegenEnabled
      ? Prop<Prop<TResolvedTypesMeta, 'resolved'>, 'matchesStates'>
      : never

It would be great to see this applied more broadly.

Expected result

Here is an example implementation with a generic StateValue. Naturally a lot of this code is to get at the typegen that would be already available within the StateNode class.

type AnyTypegen = ResolveTypegenMeta<any, any, any, any>;
type GetTypegen<T extends AnyStateMachine> = T extends StateMachine<any,any,any,any,any,any,infer T2>
  ? T2 extends AnyTypegen ? T2["resolved"] : never : never;
type StateValue<T extends AnyStateMachine> = GetTypegen<T>["matchesStates"];

const transitionSafely = <T extends AnyStateMachine>(
  machine: T,
  state: StateValue<T>,
  event: any
) => machine.transition(state, event).value as StateValue<T>;

Actual result

//'foo' should be a typescript error, and value should be 'inactive|active'
const value1 = machine.transition("foo", "TOGGLE").value;

Reproduction

https://codesandbox.io/s/xstate-typescript-demo-le9xqo?file=/src/index.ts

Additional context

No response

@davidkpiano
Copy link
Member

This is something we'll be able to do with const type generic parameters in version 5 (cc. @Andarist)

@Andarist
Copy link
Member

That's unfortunately not necessarily true. Remember that TS still doesn't support partial inference. This particular issue mentions that it's using typegen and with that, we could revamp this PR at some point: statelyai/xstate-tools#160

@davidkpiano
Copy link
Member

This is being addressed in #3940

@Andarist
Copy link
Member

We just landed this as a new feature: #4498 . Note that it requires you to use the setup API (that was also recently introduced to v5)

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

No branches or pull requests

3 participants