LoginSignup
1
0

More than 5 years have passed since last update.

TypeScriptでReactを書く際のReact.Component<>の<>に関して

Last updated at Posted at 2018-07-04

TypeScriptでReactを書く際のReact.Component<>の<>の中身

TypeScriptでReactを書いているコードを読んでいる時によく出会う
こんなコードの

test.tsx
class Test extends React.Component<any, any> {
}

この中のこれ

React.Component<any, any>

<any, any>

ってなんやねんと思っていました。
ジェネリクスっぽい...と軽く思っていましたがReact.Componentにくっついてたらどういう意味があるの?と
ずっとモヤモヤしていた中この記事に出会って解決したので書いておこうと思います。

<any, any>はPropsとStateの型定義を示している!

React.Component<any, any>

だったからわかりにくかったんです。
実際には第1引数はpropsの型、第2引数はstateの型を表しています。
<any, any>と書くと文字通り「propsもstateもどんな型でもいけるよ!」と表しているだけで

これは

interface MyProps {
   value: string
}

interface MyState {
   somevalue: string
}

class test extends React.Component<MyProps, MyState> {
}

というような感じでインターフェイスを使って
PropsとStateの型付けをするために使えます。

何か間違いがありましたら教えていただけると嬉しいです!

1
0
4

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
1
0