LoginSignup
2
1

More than 5 years have passed since last update.

render-prop で 状態を扱うコンテナコンポーネントに型を付けたい

Last updated at Posted at 2018-02-24

このコードは動いた

class WithState<State> extends React.Component<
  {
    render: (State, ((State) => State) => void) => Node
  },
  State
> {
  render() {
    return this.props.render(this.state, this.setState.bind(this))
  }
}

// -- usage --

type State = {
  value: number
}

const initialState: State = { value: 0 }
const _el = (
  <WithState
    render={(state = initialState, update: ((State) => State) => void) => {
      return (
        <button
          onClick={_ => {
            // should be error
            update(prev => ({ value: prev.value + '' }))
          }}
        >
          {state.value}
        </button>
      )
    }}
  />
)

しかし update に型をつけるのをサボるとエラーが起こらなくなる


const _el = (
  <WithState
    render={(state = initialState, update) => {
      return (
        <button
          onClick={_ => {
            // should be error
            update(prev => ({ value: prev.value + '' }))
          }}
        >
          {state.value}
        </button>
      )
    }}
  />
)

いろいろ試したが、ジェネリクスを取る引数で引数同士で型の関係があっても、一つが確定しても他に関与しない。返り値やキャストからは推論される

function f<T>(t: T, u: T => T): T {
  return u(t)
}

const s = { v: 1 }
f(s, p => {
  return { v: '' + p.v }
})

// error
const s2: { v: number } = f(s, p => {
  return { v: '' + p.v }
})

諦めて型を書くのが良さそう

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1