How To Solve “Type ‘X’ Is Missing The Following Properties From Type ‘Y’” In ReactJS

Type is missing the following properties from type

When you create a component, you use some property required in that component to run the app. If you don’t pass in enough property or do not pass any property that is required in the component, the error “Type X is missing the following properties from type Y” will occur. To solve that problem, make sure that you pass in enough property for your component to work typically.

The cause of the error “Type X is missing the following properties from type Y”?

Example :

import React from "react";
import "./App.css";
 
type ProsContainer = {
    name: string;
    age: number;
    country: string;
};
const Infor = (pros: ProsContainer) => {
    return (
        <ul>
            <li>{pros.name}</li>
            <li> {pros.age}</li>
            <li>{pros.country}</li>
        </ul>
    );
};
 
const App = () => {
  	return <Infor name=’Togban’></Infor>;
};
export default App;

The error will happen :

Type '{ name: string; }' is missing the following properties from type 'ProsContainer': age, country Type '{}' is missing the following properties from type 'ProsContainer': name, age, country

The Infor component required three property name, age, and country, but I passed in the only name property.

Solutions to fix this error

Solution 1: Passing all property required

To solve the problem, I will have to pass the remaining two properties: age and country.

Example :

import React from "react";
import "./App.css";
 
type ProsContainer = {
    name: string;
    age: number;
    country: string;
};
const Infor = (pros: ProsContainer) => {
    return (
        <ul>
            <li>{pros.name}</li>
            <li> {pros.age}</li>
            <li>{pros.country}</li>
        </ul>
    );
};
const App = () => {
  	return <Infor name='Togban' age={18} country='VietNam'></Infor>;
};
export default App;

Solution 2: Using optional

If you have some properties and it is not needed, you can mark them as optional.

Example :

import React from "react";
import "./App.css";
 
type ProsContainer = {
    name: string;
    age?: number;
    country?: string;
};
const Infor = (pros: ProsContainer) => {
    return (
        <ul>
            <li>{pros.name}</li>
            <li> {pros.age}</li>
            <li>{pros.country}</li>
        </ul>
    );
};
const App = () => {
  	return <Infor name='Togban' ></Infor>;
};
export default App;

We had a mark that age and country property is optional. So, we can ignore them without passing in value and the code is still working.

Summary

In this tutorial, I’ve explained how to solve the error “Type ‘X’ is missing the following properties from type ‘Y’” in React JS. You can pass in all properties that the component requires or set them as optional properties.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *