[英]Check types in argument of generic function and return object literal type of this argument
我有兩個接口。
interface ComponentOptions<Props> {
abstract?: boolean;
functional: boolean;
props?: Props;
name?: string;
render?(props: Props): boolean;
}
interface ComponentProps {
title: string;
dark: boolean;
}
我需要實現一個功能
Props
泛型類型Props
類型相關的任何檢查ComponentOptions<Props>
接口 strict: true
需要strict: true
編譯器選項。
我已經實現了接收兩個參數的createComponent
函數:
options
對象文字props
,被視為類型轉換的虛構參數function createComponent<
Props,
Options extends ComponentOptions<Props>
>(options: Options, props: Props): Options {
props;
return options;
}
我通過這樣的認識達到了預期的結果。 但我真的不喜歡它。
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)
我想擺脫props
參數只剩下options
,並使用通用參數設置 props 的類型,而不是強制轉換props
參數。
它可能看起來像這樣:
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
}
如何實現這一目標?
我用這個解決方案解決了我的問題:
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.