简体   繁体   中英

When migrating from Javascript to Typescript, how do you determine datatypes?

In the tutorial https://www.sitepoint.com/how-to-migrate-a-react-app-to-typescript/ I see the following JS code:

import React from 'react'
import { buttonStyles } from './Button.styles'

const Button = ({ onClick, text }) => (
  <button onClick={onClick} className={buttonStyles}>
    {text}
  </button>
)

export default Button

converted to TS:

import React, { MouseEventHandler } from 'react'
import { buttonStyles } from './Button.styles'

type Props = {
  onClick: MouseEventHandler,
  text: string,
}

const Button = ({ onClick, text }: Props) => (
  <button onClick={onClick} className={buttonStyles}>
    {text}
  </button>
)

export default Button

My question is in this case how does one know about MouseEventHandler and in general how to determine data types for the conversion? The tutorial does not seem to explain this. Also, how do you determine what goes into the state type (which is not used here, it seems)?

I also do not see how to determine what would go into props sometimes -- how is this done? I am working with a React app which was original in JS and I am dealing with a component that I am not sure needs props or if so, what they are.

In VScode you can hover an attribute to see it's type, and clicking it will lead your to it's type declaration, for example with:

 <button onClick={onClick} className={buttonStyles}>
   {text}
 </button>

it shows me in react @types:

onClick?: MouseEventHandler<T>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM