Posts > TS Basic: Interfaces

TS Basic: Interfaces

Interface declaration is another way to name an object type.

interface User {
	name: string,
	age: number,
}

function greetingUser(user: User){
	console.log(`Hello ${user.name}`);
	console.log(`Age is ${user.age}`);
}
👌TS is only concerned with the structure of the value we passed. It only cares that it has the expected properties. - Being concerned only with the structure and capabilities of type is why we call TS a structurally typed type system

Interface can also be extended to create a new interface based on the existing one.

// function example

interface User {
  name: string;
  age: number;
}

interface Employee extends User {
  employeeID: number;
  jobPosition: string;
}

function getUserName(employee: Employee): string {
  return employee.name;
}

const myEmployee: Employee = {
  name: "John Doe",
  age: 30,
  employeeID: 12345,
  jobPosition: "Software Engineer",
};

const userName: string = getUserName(myEmployee);
console.log("User Name:", userName); // Output: User Name: John Doe

// object type example

interface User {
	name: string,
	age: number,
}

interface Employee extends User {
	employeeID: number,
	jobPosition: string,
}

const employee: Employee = {
  name: "John Doe",
  age: 30,
  employeeID: 12345,
  jobPosition: "Software Engineer",
};

console.log("User Name:", employee.name);

But is it always just for object type?

While the interface are most commonly used to define the structure of objects, they can also be applied to describe other types, such as function type and array type

Function

interface MyFunction {
	(param1: number, param2: string): void;
}

const myFunction: MyFunction = (param1, param2) => {
	//rest of your code
}

Array

interface MyArray {
	[index: number]: string;
}

const myArray: MyArray = ['apple','banana','orange'];

Tags 🏷