HomeToolsAbout a20k

Interface

What is interface

interface is an abstract type that tells the compiler which property names a given object can have

interface defines the structure and types of properties or methods that an object is expected to have

  • interface is a way to define a Contract for the shape or structure of an object

interfaces are meant to declare the public contract of a Class

What is a contract

Contract is referring to a set of rules or requirements that an object must adhere to if it claims to implement or conform to a particular interface

Interface and Class Naming Convention

Class names should be capitalized

Interface should be prepended with I for distinction.

export class MockClass implements IMockClass { ... }

Syntax

interface IPerson { firstName: string; lastName: string; age: number; } // object adhering to the Person interface defined const newPerson: IPerson = { firstName: 'John', lastName: 'Doe', age: 30, };

Optional Property (?)

interface ICar { brand: string; model: string; year?: number; // Optional property }

extends

Typescript interfaces can extend Classes

extends inherits all attributes from another interface

interface IEmployee { employeeId: number; department: string; } // inherits all attributes from IEmployee type interface IManager extends IEmployee { role: string; } // instantiation uses all properties const manager: IManager = { employeeId: 123, department: 'Engineering', role: 'Manager', };

Example in React

// interface definition interface CustomComponentProps extends React.HTMLAttributes<HTMLDivElement> { children: React.ReactNode; className?: string; // optional isCustomAttribute?: boolean; } // consumption in the component export const customComponent = ({ children, className, isCustomAttribute = false, }): CustomComponentProps =>{ return ( <div className="exampleDivComponentStyling" {...divProps}> {isCustomAttribute && ( <span> "This is a custom attribute" </span> )} {children} </div> ) }
© VincentVanKoh