Basics of Typescript Built-in Types

Hello fellow Developers, recently I am learning Typescript and I want to share my knowledge and journey along the way.

Basic Typescript Types

  • Boolean
  • Number
  • String
  • Array
  • Enum
  • Void
  • Null
  • Undefined
  • Never
  • Any

Type Annotations

Type annotation is a way to describe a variable type while declaration.

let name: string = "Anna";
name = 12; //returns error

Even if you don’t annotate your variable, typescript infers your variable type on the base of the initial value.

let city = "Islamabad"; //city is type string here
city = 12; //returns error

And prevents you the assigning any value that doesn’t match with the initial value type.

Union Types

Typescript allows you to assign more than 1 type to a variable which will result in a union type.

const someVariable: string | number;
someVariable = "This is string"; //works perfectly
someVariable = 10; //works perfectly

Here someVariable can have a string value or a number value.

Type Assertions

Type assertions are used when you are getting dynamic value in your variable and then you need to perform some operation on it.

let fixedString: string = (<number>value).toFixed(4);

Here with <number> you are asserting the type of value variable as a number. In other words, you are telling your code value the variable should have a number type.
There is another way to do it

let fixedString: string = (value as number).toFixed(4);

Conclusion

In this blog, you learned about Typescript built-in types. How to Annotate and Assert variables in Typescript and last but not least How to create Union Types in Typescript.

Feel free to connect on Twitter

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How To Validate Password And Confirm Password Using JQuery

Implement Search Functionality in React js: Part-1

Created a basic Search field using React Hooks

Laravel 8 Ajax CRUD With Yajra Datatable

[Leet Code] Generate a string with characters that have odd counts

React Native Animated Splash Screens

Vlebazaar customer Care number/8584892730//8584892730/Vlebazaar customer Care…

Back-end Week 4

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aneeqa Khan

Aneeqa Khan

More from Medium

Loading Third-Party JavaScript

Javascript for application Development — (Stands of development, Introduction to javascript )

Server-Side Events as Simple Alternative to WebSockets

Top 5 Web Development Frameworks in 2021 Frontend