Basic Types in TypeScript
Linas Spukas
Posted on April 26, 2020
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:
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:
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:
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:
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.
Posted on April 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024