typing react props

https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example

summary

1.primitives(number, boolean), objects, arrays

use type when building applications and interfaces when building libraries

type PersonListProps = {

    names: {

        first: string,

        last: string

    }[]

}

export const personList = (props: PersonListProps)=>{

    return (

        <ul>{props.names.map(n=>(<li key={n.first}>{n.first}</li>))}</ul>

    )

}


2. union type

type Status = {

    status: "loading" | "success" | "error"

 }

typing template literal (based on string literal)

Exclude<,>

3. typing children props

children props, which can be passed to a react component, invoke component by pass something between the opening and closing tags

when child is a string

@types/react

what is the type of a react component: React.ReactNode, 

when child is a react component

typing component prop

passing a component as a prop

React.ComponentType

wrapping html elements

example: writing custom component and add your own types and logic

React.ComponentProps<'input'>
writing custom component

React.ComponentProps<'button'>

include button props as well as custom props

omit takes an object type and removes the specified properties

Omit<,>

extract prop types from one component and use them as prop types for another component

React.ComponentProps<typeof C>

typeof

typing polymorphic components


type generic props:

generic type, parameterized type, when you need multiple types to be handled but at the same time provide type checking

add restrains before () to let ts know what T can be

{ } includes everything: string, number, object

restricting props

example of how props should be used

ts provide type never to specify restrictions

union type

4. typing event props: click, change

half of the time, the click handle does not need any parameter and doesn't return anything, for example just make an api call

click handler
no parameter need

another variant is when you need the event passed into the click handler

@types/react

type of event: React.MouseEvent

React.MouseEvent

multiple parameter

passing another id
multiple parameter

typing an input change event

change event
value and change handler

5. typing styles

the style to be passed in as props rather than hard coded within a component

key is string, value can be number or string, but how to we restrict to only valid css properties? React.CSSProperties

passing styles
React.CSSProperties

tips:

destruct props when defining the component

exporting types

reusing types, extract a type and reuse it

export and reuse types

typing props and states for class component

use empty object if no props need to be passed: <{}, State>

if no states: <Props>

<Props, State>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容