You are here: Home / Topics / Excess Property Checks in Interface - Typescript

Excess Property Checks in Interface - Typescript

Filed under: TypeScript on 2024-03-18 11:57:41

In TypeScript, excess property checks occur when you try to assign an object literal to a variable or parameter with a defined type or interface that doesn't include all the properties of the object literal. By default, TypeScript performs excess property checks to ensure type safety and prevent potential errors.

interface Person {
   name: string;
   age: number;
}
const person: Person = {
   name: 'John',
   age: 30,
   occupation: 'Developer' // Excess property
};

In this example, the Person interface defines that an object must have name and age properties. However, when assigning an object literal to the person variable, an additional property called occupation is included. TypeScript will raise an error during compilation.


To address this error, you have a few options:
Example 1: Excess Property - Add the property to the interface
index.ts:

interface Person {
   name: string;
   age: number;
   occupation: string;
}
const person: Person = {
   name: 'John',
   age: 30,
   occupation: 'Developer'
};
console.log(person);

Example 2: Excess Property - Type Assertion
index.ts:

interface Person {
   name: string;
   age: number;
}
const person: Person = {
   name: 'John',
   age: 30,
   occupation: 'Developer' // Excess property
} as Person;
console.log(person);

Example 3: Excess Property - Assign to a fresh object
index.ts:

interface Person {
   name: string;
   age: number;
}
const person = {
   name: 'John',
   age: 30,
   occupation: 'Developer' // No error
};
function fn(person1: Person) {
   console.log(person1.name + " " + person1.age);
}
fn(person);
  

In this case, person will be inferred as having the type {  name:   string; age: number; occupation: string; }.

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.