When writing React components with TypeScript, you have two options when it comes to typing its props. You can use either type aliases or interfaces. Which one would you choose? Does it matter? Is there really an optimal choice? Are there any drawbacks to one or the other? Let's explore the relevant differences between them before we conclude.
React Typescript Functional Component Syntex, without Props..
import React from "react";
var Customer:React.FC =()=>{
return(
<div>
<h2>this is customer tsx component</h2>
</div>
)
}
export default Customer;
* To find out the react developer tools , need to install -- react developer tools
This is not a deep case study of how types aliases and interfaces differ in TypeScript, but I'll provide just a brief overview of some of the differences that are relevant to React props so we're on the same page. Later we will explore how those differences can come into play in this context.
Type aliases vs. Interfaces
Type aliases and interfaces in TypeScript are equivalent in the majority of cases. Things that you can do in one you can also do with the other with just syntax changes, and of course, there are exceptions.
Let's take a look at some examples:
Regular object with properties
type User = {
name: string;
};
// ...
interface User {
name: string;
}
React Typescript Functional Component Syntex with: Props
Step One for App.tsx ::
import React from 'react';
import Customer from './components/Customer';
import Users from './components/Users';
export default function App() {
return (
<div>
<Customer name="cgva" title="this is demo text" />
<Users userid={1} />
</div>
);
}
Step Two for Customer.tsx :: in Functional Component in TSX with Props
import React from "react";
interface IPROPS {
name : String;
title : String;
}
var Customer:React.FC <IPROPS> =({name, title})=>{
return(
<div>
<h2>this is customer tsx component</h2>
<h3>Name : {name}</h3>
<h3>Name : {title}</h3>
</div>
)
}
export default Customer;
Step Three for User.tsx :: in Class Component in TSX with Props
import React from "react";
interface IPROPS {
userid:number;
}
export default class Users extends React.Component<IPROPS>{
//eslint-disable-next-line
constructor(props:IPROPS){
super(props);
}
render() {
return (
<div>
<h2>Welcome to React TSX Class Component</h2>
<h5>UserId : {this.props.userid}</h5>
</div>
)
}
}