#Using generic types in the context of a machine

1 messages · Page 1 of 1 (latest)

patent haven
#

Hello,

Is it possible to create a machine that has a context that uses a generic type ?

Is it compatible with typegen ?

const machine = createMachine({
  schema: {
    value: T[]
  }
})
errant falcon
#

It is! Typegen is compatible with generics 👍

patent haven
#

Hello, thank you @errant falcon . Should I follow the approach described in the Github issue #3164 ? . @knotty juniper has described the process in a video companion : https://twitter.com/AndaristRake/status/1506236097042472960 . It is a quite advanced use of TypeScript. Thank you for the answer and the video.

TypeScript deeper dive 🧙‍♂️

answering open source issue & explaining how you can make your XState generics flow through the system, ending up with the best solution with instantiation expressions:

type MyService<T> = ReturnType<typeof useTabForm<T>>

https://t.co/YthsIixm9K

errant falcon
# patent haven Hello, thank you <@571685485722730511> . Should I follow the approach described...

Those are some great resources! If you just need a very basic machine, here's an example of a machine using a generic T. Feel free to post links to a sandbox or similar once you get going if you need some input 😊

export const genericsMachine = <T>() =>
  createMachine({
    initial: 'idle',
    tsTypes: {},
    schema: {
      context: {} as { data?: T },
      events: {} as
        | { type: 'Go fetch some generic data' }
        | { type: 'Event with generic data'; data: T },
      services: {} as {
        fetchSomeGenericData: { data: T };
      },
    },
    states: {
      idle: {
        on: {
          'Go fetch some generic data': 'Fetching some generic data',
        },
      },
      'Fetching some generic data': {
        invoke: {
          src: 'fetchSomeGenericData',
          onDone: {
            target: 'idle',
            actions: 'onDone', // Not included in this example
          },
          onError: {
            target: 'idle',
            actions: 'onError', // Not included in this example
          },
        },
      },
    },
  });