Facing difficulties understanding what is TypeScript and how to create custom types in TypeScript? Then you are on the right page.
TypeScript is a strongly typed programming language that builds on JavaScript. It offers optional static type-checking.
Why TypeScript is Introduced?
JavaScript is a dynamically typed language and in dynamically typed language the data type is assigned to a variable during the runtime depending on its value. Now if there is an error in your code JavaScript will detect them at the runtime. But if you use TypeScript the errors will be detected at the compile time.
How to create custom types?
Custom type can be created using the following syntax.
Syntax:
type User = {
name: string;
email: string;
age: number;
};
We can also create custom type using interface keyword.
interface User{
name: string;
email: string;
age: number;
};
Till now, we have learned how to create custom types in TypeScript. Next, we will see how to use them.
Example:
let demoUser: User = {
name: "John",
email: "john1234@gmail.com",
age: 18
};