React · Lesson 60 of 120
React with TypeScript
Typed props.
Most new React projects use TypeScript. It checks your props and state as you type, so mistakes show up in the editor, not in the browser.
- Most projects
- Checks props
- Mistakes found early
Typed props
With TypeScript, the file ends in t s x. A type describes a product. Card props describes the props, and on add is optional. If App forgets a prop, or passes the wrong type, the editor shows an error straight away. We click add. Run it.
App.tsxtsx
type Product = { id: number; name: string; price: number; stock: number };
type CardProps = { product: Product; onAdd?: (id: number) => void };
function ProductCard({ product, onAdd }: CardProps) {
return (
<div className="box">
<b>{product.name}</b> £{product.price}
{onAdd && <button id={"a" + product.id} onClick={() => onAdd(product.id)}>Add</button>}
</div>
);
}
export default function App() {
const trail: Product = { id: 1, name: "Trail 500", price: 849.5, stock: 12 };
return <ProductCard product={trail} onAdd={id => console.log("added product", id)} />;
}Output
added product 1
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#a1"}]Typing props
Write a type for each component's props. Mark optional ones with a question mark. Children are typed as React node. And function props describe their arguments and return type.
| key | value |
|---|---|
| Props | type CardProps = {...} |
| Optional | onAdd? |
| Children | React.ReactNode |
| Functions | (id: number) => void |
Summary
Type your props, and TypeScript checks every component that uses them. Next, typing state and events.
Key takeaways- .tsx
- type Props
- Checked usage
Next up: Typing State and Events — useState<T>