https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/basic_type_example
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)
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
@types/react
what is the type of a react component: React.ReactNode,
typing component prop
passing a component as a prop
wrapping html elements
example: writing custom component and add your own types and logic
React.ComponentProps<'button'>
omit takes an object type and removes the specified properties
extract prop types from one component and use them as prop types for another component
React.ComponentProps<typeof C>
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
{ } includes everything: string, number, object
restricting props
ts provide type never to specify restrictions
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
another variant is when you need the event passed into the click handler
@types/react
type of event: React.MouseEvent
multiple parameter
typing an input change event
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
tips:
destruct props when defining the component
exporting types
reusing types, extract a type and reuse it
typing props and states for class component
use empty object if no props need to be passed: <{}, State>
if no states: <Props>