[英]Check types in argument of generic function and return object literal type of this argument
I have two interfaces.我有两个接口。
interface ComponentOptions<Props> {
abstract?: boolean;
functional: boolean;
props?: Props;
name?: string;
render?(props: Props): boolean;
}
interface ComponentProps {
title: string;
dark: boolean;
}
I need to realize a function that我需要实现一个功能
Props
generic type需要一个接口来替代Props
泛型类型Props
type in function argument object执行与函数参数对象中的Props
类型相关的任何检查ComponentOptions<Props>
interface不返回ComponentOptions<Props>
接口strict: true
compiler option required. strict: true
需要strict: true
编译器选项。
I have implemented createComponent
function that recieves two arguments:我已经实现了接收两个参数的createComponent
函数:
options
object literal必需的options
对象文字props
, treated as imaginary argument for type casting props
,被视为类型转换的虚构参数function createComponent<
Props,
Options extends ComponentOptions<Props>
>(options: Options, props: Props): Options {
props;
return options;
}
I achieved the desired result with such an realization.我通过这样的认识达到了预期的结果。 But I don't really like it.但我真的不喜欢它。
const component = createComponent({
abstract: true,
functional: true
}, {})
const componentWithProps = createComponent({
functional: false,
name: 'bar',
props: {
title: 'bar',
dark: true
},
render(props) {
return props.dark
}
}, {} as ComponentProps)
I want to get rid of props
argument to left only options
, and to set the type for props using a generic parameter, not casting the props
argument.我想摆脱props
参数只剩下options
,并使用通用参数设置 props 的类型,而不是强制转换props
参数。
It might look like this:它可能看起来像这样:
const component = createComponent<ComponentProps>({
functional: true,
props: { // Check 'title' and 'dark' types
title: 'comp',
dark: true
},
render(props) { // Pass type for the props
return props.dark;
}
})
// When we hover on `component` variable,
// display all defined properties in the `options`
{
functional: true,
props: ComponentProps,
render(props: ComponentProps): boolean
}
How to achieve this?如何实现这一目标?
I solved my problem with this solution:我用这个解决方案解决了我的问题:
interface FunctionalComponent<Props> {
<Options extends ComponentOptions<Props>>(opts: Options): Options
}
function createFunctionalComponent<Props = {}>() {
return (o => o) as FunctionalComponent<Props>;
}
const component3 = createFunctionalComponent<ComponentProps>()({
functional: false,
name: 'bar',
props: {
title: 'bar',
dark: true
},
render(props) {
return props.dark
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.