colebemis / glamorous-prop-styles

:lipstick: Easily create glamorous components that accept props to enable/disable styles
MIT License
9 stars 4 forks source link

Typescript types #1

Open thomhos opened 7 years ago

thomhos commented 7 years ago

Hello,

I've wrote a quick starting point for type annotations for this function. The below works, but there's one 'any' in there that I can't seem to get rid of. The values in the 'styles' parameter can be 'CSSProperties', 'CSSProperties[]' or a function that returns any of the former.

Anyone know how to solve that?

Otherwise the work in progress is below;

import { CSSProperties } from 'glamorous'

export function propStyles<P>(styles: {[key in keyof P]: any }) {
    return function dynamicStyles(props: P): CSSProperties[] {
        return Object.keys(props).map((key: keyof P): CSSProperties => {
            if (props[key]) {
                return typeof styles[key] === 'function'
                    ? styles[key](props)
                    : styles[key]
            }
            return undefined
        })
    }
}
thomhos commented 7 years ago

I've revised these annotations to the below, which works. But I'm having a bit of difficulty translating this to a .d.ts file..

import glamorous, { CSSProperties, StyleArgument } from 'glamorous'

type StyleObject<P> = {
  [key in keyof P]: StyleValue<P>
}

type StyleValue<P> = StyleArgument<CSSProperties, P> | StyleArray<P>
interface StyleArray<P> extends Array<StyleValue<P>> {}

export function propStyles<P>(styles: StyleObject<P>): (props: P) => StyleArgument<CSSProperties, P>[] {
    return function dynamicStyles(props: P): StyleArgument<CSSProperties, P>[] {
        return Object.keys(props).map((key: keyof P): StyleArgument<CSSProperties, P> => {
            const style = styles[key]
            if (style) {
                return (typeof style === 'function') && !(style instanceof Array)
                    ? style(props)
                    : style as StyleArgument<CSSProperties, P>
            }
            return undefined
        })
    }
}