如何定义类型取决于函数参数

时间:2018-07-17 05:20:39

标签: typescript react-native high-order-component

我想通过以下示例定义“ WithStyles”的界面:

import { withStyles, WithStyles } from '@theme/helper/context'
import React from 'react'
import { Text, View } from 'react-native'
import { compose } from 'recompose'


export const styles = (theme: TThemeStyle) => {
	console.log('Theme', theme)
	const { appStyle } = theme
	return StyleSheet.create({
		container: appStyle.container.padding,
	})
}
 
interface ToDoSinglePropsOut {

}
interface ToDoSinglePropsIn extends ToDoSinglePropsOut, WithStyles<typeof styles>{
}

const TodoSingle = ({ styles }: ToDoSinglePropsIn) => (
	<View style={styles.container}>
		<Text>
			Todo Single
		</Text>
	</View>
)

export const TodoSingleScreen = compose<ToDoSinglePropsIn, ToDoSinglePropsOut>(withStyles(styles))(TodoSingle)

我已经定义了WithTypes,如下所示。但这仅返回{styles:any}。这完全没有道理。目的WithType是返回参数函数的结果。例如上面的例子:我希望样式会像这样:{styles:{container:any}}。取决于参数的功能

export const ThemeContext = React.createContext(getTheme())

export function withStyles<T extends TStyle, U extends object>(getStyle:  (style: T) => U) {
	return function (Component: React.ComponentClass<{}>) {
		const ThemeComponent = (props: any) => {
			return (
				<ThemeContext.Consumer>
				{(theme: T) => (
					<Component {...props} styles={getStyle(theme)}/>

				)}
				</ThemeContext.Consumer>
			)
		}
		return ThemeComponent
	}
}

export interface WithStyles<T> {
	styles: any
}

0 个答案:

没有答案