Careeroza
Defining Interfaces
The interface Keyword
An interface is another way to name an object type. It can describe properties, optional and readonly properties, and methods.
Example
interface Product {
readonly id: number;
name: string;
price: number;
discountPercent?: number;
finalPrice(): number;
}
const phone: Product = {
id: 11,
name: "ShopEase Phone X",
price: 19999,
discountPercent: 10,
finalPrice() {
return this.price - (this.price * (this.discountPercent ?? 0)) / 100;
},
};
console.log(phone.name, "->", phone.finalPrice());Output
ShopEase Phone X -> 17999.1
Missing Method
Example
An object must implement everything the interface requires (TS2741).
interface Greeter {
name: string;
greet(): string;
}
const g: Greeter = { name: "Bot" };Compiler output (tsc)
Line 6: error TS2741: Property 'greet' is missing in type '{ name: string; }' but required in type 'Greeter'.