High-level overview of type and interface in Typescript
Meet Vaghasiya
Passionate Vue.js & Laravel Developer | JavaScript Lover | Eager to Learn
Standard javascript object is a map of key: value pairs. When we define an object with properties (keys) and values, TypeScript creates an?implicit interface?by looking at the property names and data types of their values in the object. This happens because of the?type of inference. or we can explicitly gives type to object.
If we create the same type of object then we need to too much copy-paste for the same object also if want to change in object structure like age will be a string instead of number, then we have to go everywhere to change the type.
We can solve this type of issue using type or interface.
Type keyword:
The type keyword is a way to describe a type alias for variables, objects, and functions. This alias essentially describes what our data look likes. we can describe data by their type string, number, boolean, etc.
We can create types for string,number,boolean , tuples also.
We can combine more than one type using &. if any property we miss from combined types, then typescript will give an error.
Interface
An interface is the shape of javascript. the interface is just like an object but it only contains information about the key and their types.
Let's convert types examples in the interface and then understand the difference.
领英推荐
We need to extend keywords to inherit property from another interface.
We need to extend keywords in class to the user interface
Difference between interface and type:
type Age = number;
type Price = number | string ;
const age : Age = 24;
const price: Price = 9999