You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为Storybook编写TypeScript全局装饰器遇编译错误,求助解决

Storybook + TypeScript 全局装饰器编译错误解决

你在编写接收Story与context参数的全局装饰器时遇到编译错误,代码如下:

const CustomDecorator = (Story, context) => {
  console.log("My Decorator");
  return (
      <Story />
  );
};

const preview: Preview = {
  decorators: [CustomDecorator],
  parameters: {
    actions: { argTypesRegex: "^on[A-Z].*" },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },

  globalTypes: {
    theme: {
      description: 'Global theme for components',
      defaultValue: 'light',
      toolbar: {
        // The label to show for this toolbar item
        title: 'Theme',
        icon: 'circlehollow',
        // Array of plain string values or MenuItem shape (see below)
        items: ['light', 'dark'],
        // Change title based on selected value
        dynamicTitle: true,
      },
    },
  },
};

编译时触发错误:

Failed to compile.
Syntax error: Unexpected token, expected "," (8:13)
storybook/preview.ts undefined

   6 |   console.log("My Decorator");
   7 |   return (
>  8 |       <Story />
     |              ^
   9 |   );
  10 | };
  11 |

VSCode中hover <Story />时提示:'Story' refers to a value, but is being used as a type here. Did you mean 'typeof Story'?


问题原因与解决方法

这个错误的核心是TypeScript无法识别Story的组件类型,同时Storybook装饰器中的Story本质是一个函数组件,需要正确调用或声明类型。

方法1:直接调用Story函数

将JSX写法的<Story />改为函数调用形式,因为Story本身就是一个可执行的函数:

const CustomDecorator = (Story, context) => {
  console.log("My Decorator");
  return Story();
};

方法2:添加类型声明

导入Storybook的装饰器类型,明确Story和context的类型,让TypeScript正确识别Story为组件:

import { Decorator } from '@storybook/react';

const CustomDecorator: Decorator = (Story, context) => {
  console.log("My Decorator");
  return <Story />;
};

如果需要给Story传递参数,可以通过以下方式:

// 函数调用式传参
return Story({ args: context.args });
// 或JSX式传参(添加类型后)
return <Story {...context.args} />;

内容的提问来源于stack exchange,提问作者Harsh Narwariya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:45:21