Search⌘ K

Weak Types in Interfaces

Explore the concept of weak types in TypeScript interfaces, defined by optional properties, and understand how this impacts type checking and compiler errors. Learn to adjust interface definitions to maintain strong typing and avoid common pitfalls with optional property structures.

Introduction to weak types

When we define an interface where all of its properties are optional, this is considered to be a weak type. In other words, we have defined an interface, but none of the properties of the interface are mandatory.

Let’s see what happens if we create a weak type and then try to bend the standard type rules as follows:

TypeScript 4.9.5
// Interface `IWeakType` defines the structure of a weak type object with optional properties `id` and `name`
interface IWeakType {
id?: number;
name?: string;
}
// `weakTypeNoOverlap` is a variable that is assigned an object that does not match the structure defined by `IWeakType`
// The object has a `description` property, which is not part of the `IWeakType` definition
let weakTypeNoOverlap: IWeakType = {
description: "a description",
};
Weak types in interfaces
  • We define an interface name IWeakType ...