Home > Web Front-end > JS Tutorial > Understanding Type and Interface in Typescript

Understanding Type and Interface in Typescript

DDD
Release: 2024-12-31 20:44:14
Original
182 people have browsed it

Understanding Type and Interface in Typescript

Interface

What is interface:

  • An interface is a way to define the shape or structure of an object in Typescript.
  • It is primarily used to describe the blueprint for object, ensure that they adhere to a specific structure.

Key Features:

1. Used for Object Structure

  • Defines properties, method and their types.
interface User {
username: string, 
password: string,
email?: string // this is optional property
}

Copy after login
Copy after login

2. Suports Extending:

  • Interface can extend other interfaces to inherit properties.
interface Address {
street: string,
city: string
}
interface User extends Address {
username: string,
password: string,
email?: string
}

Copy after login
Copy after login

3. Class can implement interfaces:

  • Enforces that a class adheres to the interface structure.
class Admin implements User {
  username: string
  password: string
  email?: string
  street: string
  city: string

  constructor(username: string, password:string, street:string, city:string, email?:string){
    this.username = username;
    this.password = password;
    this.email = email || '';
    this.street = street;
    this.city = city;
  };
}

var aAdmin = new Admin("user1", "123", "3/2 street", "hcmc");
console.log(aAdmin);

Copy after login
Copy after login

output:

Admin {
  username: 'user1',
  password: '123',
  email: '',
  street: '3/2 street',
  city: 'hcmc'
}

Copy after login

4. Can declare function

  • Interfaces can declare function signatures
interface AddUser{
  (name: string) : void;
}

const user : AddUser = (name) => console.log(`Hello ${name}`);
Copy after login

Type

What is Type:

  • A type is a flexible way to define a type alias for almost anything in Typescript.
  • It can describe objects, unions, intersections, tuples, and more.

Key Features:

1. Alias for any type:

  • Can define primitive types, objects, or even unions and intersections.
type UserType = {
  id: string,
  name: string
}
type ID = string | number; //Union type


Copy after login

2. Support Intersection Types:

  • Combine multiple types into one
type UserType = {
  id: string,
  name: string
}

type AddressType = {
  street: string,
  city: string,
}
type UserWithAddress = UserType & AddressType;
Copy after login

3. Support Tuples:

  • Can define fixed-length arrays with specific types for each element.
type Coordinates = [number, number];
const point: Coordinates = [10, 20];

Copy after login

4. Cannot be reopened:

  • Unlike interfaces, you cannot redeclare or extend an existing type.
class AdminType extends UserType {
  // ERROR: 'UserType' only refers to a type, but is being used as a value here.ts(2693)
}
Copy after login

Key differences between Interface and Type

Aspect Interface Type
Usage Define Object structure Flexible: can be define objects, unions, intersections, tuples.
Extensibility Can be extended using extends Can be combined using & (intersection).
Reopen/Declartion Can be reopened to add new properties. Cannot be reopened.
Primitive Type Cannot represent primitives directly. Can alias primitive (e.g,.type ID = string);
Union and Typle Support Not supported. Fully supported
Aspect
Interface Type
Usage Define Object structure Flexible: can be define objects, unions, intersections, tuples.
Extensibility Can be extended using extends Can be combined using & (intersection).
Reopen/Declartion Can be reopened to add new properties. Cannot be reopened.
Primitive Type Cannot represent primitives directly. Can alias primitive (e.g,.type ID = string);
Union and Typle Support Not supported. Fully supported

When to User Interface vs. Type

Use Interface:

  • When describing the shape of an object or when working with classes.
interface User {
username: string, 
password: string,
email?: string // this is optional property
}

Copy after login
Copy after login

Use Type:

  • When defining union or tuples, or any advanced type definitions.
interface Address {
street: string,
city: string
}
interface User extends Address {
username: string,
password: string,
email?: string
}

Copy after login
Copy after login

Combining Type:

class Admin implements User {
  username: string
  password: string
  email?: string
  street: string
  city: string

  constructor(username: string, password:string, street:string, city:string, email?:string){
    this.username = username;
    this.password = password;
    this.email = email || '';
    this.street = street;
    this.city = city;
  };
}

var aAdmin = new Admin("user1", "123", "3/2 street", "hcmc");
console.log(aAdmin);

Copy after login
Copy after login

Best Practise:

  1. Use interface for describing object and Type for everything else.
  2. Use Type for more advanced use cases like unions or intersections.
  3. Choose interface for consistency if you work in a team that refers it

The above is the detailed content of Understanding Type and Interface in Typescript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template