Table of contents
Before going to Typescript let's understand some theory of Typescript. Why should we use Typescript and why Typescript was made to overcome issues in javascript. If you ever work with C++ and Java these are statically Typed language which means we have to declare the data type before compilation on the other hand languages like Python and javascript they are dynamically typed which means data types are decided during run time. Javascript is even loosely typed which means we will not get error if we perform same operation on two different data type. Let's understand with an example
let a = 10;
let b = “10“;
console.log(a+b);
// output 1010
These things can be a measure issue in development when we are working with a team. Which can create measure bugs. To solve all these issues developer introduced Typescript which is a wrapper over javascript to provide type safety. Let's setup Typescript in our environment
npm install -g typescript
React + Typescript
If you already know javascript and work with react and javascript. It would be so easy for you to understand the React with Typescript
- Functional component in Typescript
const myButton: React.FC()=>{
return <button>Click Me</button>
};
- Passing props
const myButton = (props:{text:string}))=>{
return <button>{props.text}</button>
};
// Not a preferred way of passing props
interface MyButtonProps{
text:string;
}
const myButton : React.FC<MyButtonProps>=(props)=>{
return <button>{props.text}</button>
};
// This is the preferred way of passing the props
You may have confusion regarding the interface. Let me clear that Interface is used in defining the shape of Object. It defines the properties and methods that must have an object.
- Hooks in React and Typescript
- Implicit Type in useState hook - In implicit Type we do not declare the type but on the basis of initial value typescript assumes the type of state.
const [value,setValue] = useState(1)
// It will assume Type:Number
- Explicit Type - Here we explicitly declare the type of hook.
const [value,setValue] = useState<number|null>(1);
- Passing an object in useState hook -
interface Book{
name:string;
price:number;
}
interface MyButtonProps{
text:string;
}
const myButton: React.FC<MyButtonProps>=(props)=>{
const [value, setValue] = useState<Book>({
name:"Mahabharat",
price: 200
})
}
- Form handling in React js and Typescript
const [value, setValue] = useState<string|undefined>();
const handleChangeEvent = (e:React.ChangeEvent<HTMLInputElement>)=>{
setValue(e.target.value);
}
// React.ChangeEvent is name of the event here we're handling change event
// Let's understand submit event
const handleSubmit = (e:React.FormEvent<HTMLFormElement>)=>{
e.preventDefault();
console.log(e)
}
Here, we told you about many things in react and Typescript there are much more concepts to learn in Typescript. If you want to explore further you can go to this link