Typescript_interfaces_1688031893
Typescript_interfaces_1688031893
Interfaces
© Ritik
Banger
Disclaimer
© Ritik Banger
© Ritik Banger
Understanding
TypeScript Interfaces
© Ritik Banger
interface
in TypeScript
interface name
interface Person {
name: string; name and type of
age: number; properties
};
© Ritik Banger
Working
with TypeScript interface
Interfaces support contract-based
programming, enabling clear
communication and agreement on the
expected structure and behavior of
objects in TypeScript code.
© Ritik Banger
Optional
Properties
Interfaces can have optional properties
denoted by a "?" after the property name.
interface Book {
title: string;
author: string;
year?: number;
};
© Ritik Banger
Optional
Properties
If you provide with properties that does
not exist in interface, you will get an error
like this
© Ritik Banger
Readonly
Properties
Interfaces can have readonly properties
that cannot be modified after initialization.
interface Point {
readonly x: number;
readonly y: number;
};
const point: Point = {
x: 5,
y: 10,
};
© Ritik Banger
Function
Types
Interfaces can define the shape of a
function, including parameter types and
return types.
interface MathOperation {
(x: number, y: number): number;
};
© Ritik Banger
Extending
Interfaces
Interfaces can extend other interfaces,
inheriting their properties and adding new
ones.
interface Shape {
color: string;
};
© Ritik Banger
Implementing
Interfaces
Classes can implement interfaces,
ensuring they adhere to the defined
structure.
interface Printable {
print(): void;
};
© Ritik Banger
Generic
Interfaces
Interfaces in TypeScript can also be
generic, allowing for flexibility and
reusability.
© Ritik Banger
Example:
interface Box<T> {
value: T;
};
console.log(numberBox.value); // Output: 42
© Ritik Banger
Explanation:
In this example, we have a generic
interface called Box<T>, which represents
a simple box that can hold a value of any
type T. The value property within the Box
interface is of type T.
type Person = {
name: string;
age: number;
};
interface Person {
name: string;
age: number;
};
© Ritik Banger
Types v/s Interfaces
Interfaces support declaration merging,
allowing you to define multiple interface
declarations with the same name, and
they are merged into a single interface
with the combined properties while Types
do not support declaration merging.
© Ritik Banger
Don't forget to
Like, Comment, and Repost
© Ritik Banger