Typescript - Types vs Interface

ยท 469 words ยท 3 minute read

Types ๐Ÿ”—

A type helps in defining the shape or structure of the javascript value. A type can consist of a single property or method or can have combination of multiple properties and methods.

For example, the type of variables below can be inferred by typescript by checking the values assigned to them.

let id = 123; //number
let name = "Gagandeep Singh"; //string
let skills = ["typescript", "react"]; // string[]

But in case of an object or complex data structure it’s good to define a type beforehand. Adding or removing a property will result in compile time error.

type User = {
  name: string;
  id: number;
  age: number;
};

const user1: User = {
  name: "John",
  id: 123,
  age: 30,
};

We can also have a literal type while defining types. Which means narrowing the values to what can be assigned to a variable. In below example we can only have one of 3 values (“programmer” | “manager” | “support”) that can be assigned to occupation. ? means a property is optional.

type User = {
  name: string;
  id: number;
  age: number;
  occupation?: "programmer" | "manager" | "support";
};

const user1: User = {
  name: "John",
  id: 123,
  age: 30,
  occupation: "manager",
};

Not defining an initial value or type to a variable makes it any type. Any type of value can be assigned to a variable of type any. The below example code is valid since ‘a’ is of type any.

let a;
a = 10;
a = {
  id: 123,
};
a = "some string";

types can also be used to define a structure of a function. For example, below function accepts two string values as input and returns a string. Accepting or returning something else will lead to an error and in case nothing is returned we can use void

type getFullnameType = (firstname: string, lastname: string) => string;
type printFullnameType = (firstname: string, lastname: string) => void;

Interface ๐Ÿ”—

Interfaces in typescript has similar usage as Types expect few differences.

  1. Interface use the interface keyword to define but can be used how we would use a type.
interface User {
  name: string;
  id: number;
  age: number;
}
  1. An interface can extend another interface but types cannot do so.
interface User {
  name: string;
  id: number;
  age: number;
}

interface Admin extends User {
  hasAdminRights: boolean;
}
  1. A class can implement an interface but not a type
interface User {
  name: string;
  id: number;
  age: number;
}

interface Admin extends User {
  hasAdminRights?: boolean;
}

class CreateUser implements Admin {
  name: string;
  id: number;
  age: number;
  hasAdminRights: boolean | undefined;

  constructor(props: Admin) {
    this.name = props.name;
    this.id = props.id;
    this.age = props.age;
    this.hasAdminRights = props.hasAdminRights;
  }
}
  1. Interfaces cannot be used to define literal or primitive types.
  interface occupation = "programmer" | "manager" | "support"; // incorrect