Repository navigation
How to define a type of the context passed to the play function in CSF4?
#33983
SummaryI need to create a shared interactive test step that receives the play: async (context) => {
...
await openDetachedAnnotationsDialogStep(context);const openDetachedAnnotationsDialogStep = async (context: ???) => {Unfortunately, I can't find a clear way to define the type of the I can't use the too broad Moreover, in CSF4, I can't "hack" my way around using the type extraction, unlike in CSF3! type Story = StoryObj<typeof meta>;
type StoryPlayFunction = WithRequiredProp<Story, 'play'>['play'];
type StoryPlayContext = Parameters<StoryPlayFunction>[0];const openDetachedAnnotationsDialogStep = async (context: StoryPlayContext) => {On the caller side, I'll get the following TS error: Additional informationCreate a reproductionhttps://stackblitz.com/edit/github-phyknskg?file=src%2Fstories%2FButton.stories.ts |
Replies: 2 comments 2 replies
|
Hi @oleksandr-danylchenko! I'm Dosu and I’m helping the storybook team. For reusable play function helpers in CSF4, you can use import type { PlayFunctionContext } from 'storybook/internal/types';
import type { ReactRenderer } from '@storybook/react';
// Generic helper that preserves args type
const openDetachedAnnotationsDialogStep = async <TArgs = any>(
context: PlayFunctionContext<ReactRenderer, TArgs>
) => {
const { canvasElement, step } = context;
// ...
};The generic export const MyStory: Story = {
play: async (context) => {
await openDetachedAnnotationsDialogStep(context); // TArgs inferred from story
},
};Note: To reply, just mention @dosu. Share context across your team and agents. Try Dosu. |
|
Use the renderer and the component's prop type as the two type arguments to import type { ComponentProps } from 'react';
import type { ReactRenderer } from '@storybook/react';
import type { StoryContext } from 'storybook/internal/csf';
import { expect } from 'storybook/test';
type ButtonPlayContext = StoryContext<
ReactRenderer,
ComponentProps<typeof Button>
>;
async function checkButton({ args, canvas, step }: ButtonPlayContext) {
await step('Check the button', async () => {
await expect(canvas.getByRole('button', { name: args.label })).toBeVisible();
});
}
export const Basic = meta.story({
args: { label: 'Open' },
play: async (context) => {
await checkButton(context);
},
});In strict TypeScript tests with Storybook 10.2.11 and 10.6.6,
|

Use the renderer and the component's prop type as the two type arguments to
StoryContext. That gives the shared step the sameargsshape without extracting a parameter from the overloadedmeta.storymethod.