如何编写泛型,以便Result接受提供给泛型的另一种类型的参数?
这是我的示例代码。
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;
这是可行的,但它并不特定于传递给它的参数,这就是为什么我想要一个通用的:
// 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;
// };
我们在故事书中使用这样的泛型:
也许你可以做类似的事情
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),
}
我喜欢助手函数的想法,所以我四处玩耍。它确实在函数内部强制转换为any
,但这与它的用法无关。
import React from "react";
import { Meta, Story } from "@storybook/react";
import { Box, BoxProps } from "./Box";
type BindTemplate = <T extends Story<any>>(template: T, args: T["args"]) => T;
const bindTemplate: BindTemplate = (template, args) => {
const boundTemplate = (template as any).bind({});
boundTemplate.args = args;
return boundTemplate;
};
const config: Meta = {
title: "Box",
component: Box,
};
export default config;
const Template: Story<BoxProps> = (args) => <Box {...args}>lol</Box>;
export const Primary = bindTemplate(Template, {
className: "valid",
someInvalidProps: "invalid",
});