Skip to content

Instantly share code, notes, and snippets.

@killtheliterate
Last active June 13, 2018 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killtheliterate/a21ffc83d07ce69cfbe6dad1afc5707e to your computer and use it in GitHub Desktop.
Save killtheliterate/a21ffc83d07ce69cfbe6dad1afc5707e to your computer and use it in GitHub Desktop.
Spread operator loses type information
import * as React from 'react'
import { shallow } from 'enzyme'
// ---------------------------------------------------------------------------
export type HocProps = {
a: boolean
b: boolean
}
export function HOC <P> (CC: React.ComponentType<P>) {
return class Eff extends React.Component<P & HocProps, {}> {
render () {
const { a, b, ...restProps } = this.props as HocProps
return (<CC {...restProps}/>)
}
}
}
describe('...wut', () => {
it('Higher-order components do not work well with restProps', () => {
function render<P> (CC: React.ComponentClass<P>, restProps: P) {
return shallow(<CC { ...restProps } />)
}
const CC = () => (<div>A component</div>)
const Wrapped = HOC(CC)
render(Wrapped, { a: true, b: true }) // compiles :)
render(Wrapped, { a: true, b: 'yay' }) // does not compile :)
render(Wrapped, { a: true }) // compiles :(
render(Wrapped, { a: true }) // compiles :(
// -----------------------------------------------------------------------
const Derived = ({ c }: { c: string }) => (<div>{ c }</div>)
const DerivedWrapper = HOC(Derived)
render(DerivedWrapper, { a: true, b: false }) // compiles :)
render(DerivedWrapper, { a: true, b: false, c: 'hey' }) // compiles :)
render(DerivedWrapper, { a: true, b: false, c: false }) // does not compile :)
render(DerivedWrapper, { a: true }) // compiles :(
render(DerivedWrapper, { a: true, c: 'wut' }) // compiles :(
render(DerivedWrapper, {}) // compiles :(
})
it('Higher-order components work fine if they\'re called as JSX', () => {
const CC = () => (<div>A component</div>)
const Wrapped = HOC(CC)
shallow(<Wrapped a b />) // compiles :)
shallow(<Wrapped />) // does not compile :)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment