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
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 ConventionClass
names should be capitalized
Interface
should be prepended with I
for distinction.
export class MockClass implements IMockClass { ... }
interface IPerson { firstName: string; lastName: string; age: number; } // object adhering to the Person interface defined const newPerson: IPerson = { firstName: 'John', lastName: 'Doe', age: 30, };
?
)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', };
// 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> ) }