如何创建绑定故事书控件参数的通用打字稿函数

Ste*_*lin 3 typescript reactjs typescript-generics storybook

如何编写泛型,以便结果采用提供给泛型的另一种类型的参数?

这是我的示例代码。

import { Story } from '@storybook/react/types-6-0';

type TKeyAny = {
  [key: string]: string; // | 'other args values here...';
};

// this fails
export const bindargs = <A extends TKeyAny, T extends Story<A>>(args: A, Template: T): T => {
  const Comp = Template.bind({});
  Comp.args = args;
  return Comp;
};

export default bindargs;
Run Code Online (Sandbox Code Playgroud)

这可以工作,但它并不特定于传递给它的参数,这就是为什么我想要一个通用的:


// This works but I'd like this instead to be in a generic 
// export const bindargs = (args: TKeyAny, Template: Story<TKeyAny>): Story<TKeyAny> => {
//   const Comp = Template.bind({});
//   Comp.args = args;
//   return Comp;
// };
Run Code Online (Sandbox Code Playgroud)

Alf*_*sen 5

我们在 Storybook 中使用这样的泛型:

也许你可以做类似的事情

import React from 'react'
import { Meta, Story } from '@storybook/react/types-6-0'

import SelectDropdown, { ISelectDropdownProps, SelectOption } from './SelectDropdown'

export default {
  title: 'Shared/Components/SelectDropdown',
  component: SelectDropdown,
  argTypes: {
    options: {
      control: {
        type: 'object',
      },
    },
(...)
} as Meta


const Template = <T extends {}>(): Story<ISelectDropdownProps<T>> => args => (
  <div
    style={{
      width: '300px',
    }}
  >
    <SelectDropdown<T> {...args} />
  </div>
)

export const Normal = Template<number>().bind({})
Normal.args = {
  options: createOptions(5),
}
Run Code Online (Sandbox Code Playgroud)