Type

Types in TypeScript are used to define custom types that can be used to represent a shape or structure of an object. Types can represent any valid type in TypeScript, including primitive types, union types, intersection types, etc. Types can be used for creating aliases of existing types, making complex types more readable and reusable.

Syntax

type MyType = {
    // Type properties and methods
}

Example

In this example, we will see the implementation of Type.

Javascript




// type.ts
type Point = {
    x: number;
     y: number;
};
  
const point: Point = {
    x: 10,
    y: 20,
};
  
console.log(point.x); 
console.log(point.y);


Output

10    // point.x
20    // point.y

TypeScript Interface vs Type Statements

In TypeScript, both “interface” and “type” statements are used to define the shape or structure of an object or a type. They provide a way to define custom types and enforce type checking in TypeScript code. However, there are some differences between the two.

Similar Reads

Interface

Interfaces in TypeScript are used to define agreements for objects. They can contain properties, methods, and method signatures. Interfaces can be implemented by classes to enforce a specific structure and ensure that the class adheres to the contract defined by the interface. Interfaces support multiple inheritance, where a class can implement multiple interfaces....

Type

...

Difference between Interface and type Statements

Types in TypeScript are used to define custom types that can be used to represent a shape or structure of an object. Types can represent any valid type in TypeScript, including primitive types, union types, intersection types, etc. Types can be used for creating aliases of existing types, making complex types more readable and reusable....