DEV Community

Linas Spukas
Linas Spukas

Posted on

3 3

Basic Types in TypeScript

TypeScript adds optional static types to JavaScript. A Type in TypeScript means a reference to the value and all its methods and properties. And a Value in JavaScript (and TypeScript) is anything that can be assigned to a variable. That includes String, Boolean, Array, and so on. There are two value categories:

  • Primitives: Boolean, Number, String, Symbol, null
  • Objects: Array, Object, Function, Class

If we take for example a String data type, it includes many methods and properties, such as length, toUpperCase(), indexOf(), split() and many more. And if we create value by assigning that string to a variable, we will get a Type that will reference to all properties and methods of the string.

All values have a type:

"red car" // a type of String
42        // a type of Number
["one"]   // a type of Array
true      // a type of Boolean

interface Car {
  color: string;
  year: number;
}

{ color: "red", year: 1973 } // an object, a type of Car

Types are essential to TypeScript because the compiler is using them to search and analyses for possible bugs and errors. If you have defined a type of Car with properties color and year, the compiler will make sure that only these properties will exist in a value that you assign the Car type.

Type Annotations

TypeScript also uses types to annotate values. If we create a value of Date and hover over that value, the code editor will show you what type does this value belong to:

Alt Text

Also, it recognizes all the methods and properties this type has. When referencing this value with a dot, and autocomplete will list you all the properties this type has:

Alt Text

And will notify if you try to access undefined methods for this type. It is the best part of Typescript. You will be notified before running your code:

Alt Text

Another example of type annotation when values do not have a predefined type name, just a plain object. Then by default the compiler list all the methods in that object with values and not a short name:

Alt Text

Summing up

TypeScript is based on types. Everything you write, you'll be using types, and a compiler will make sure you won't leave errors and get pretty and helpful annotations.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more