HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
TypeScript supports some simple types (primitives) you may know
When creating a variable, there are two main ways TypeScript assigns a type:
In both examples below firstName
is of type string
let firstName: string = "Dylan";
let firstName = "Dylan";
Note: Having TypeScript "guess" the type of a value is called infer.
Implicit assignment forces TypeScript to infer the value.
TypeScript will throw an error if data types do not match.
let firstName: string = "Dylan"; // type string
firstName = 33; // attempts to re-assign the value to a different type
firstName
less noticeable as a string
, but both will throw an error:
let firstName = "Dylan"; // inferred to type string
firstName = 33; // attempts to re-assign the value to a different type
TypeScript may not always properly infer what the type of a variable may be. In such cases, it will set the type to any
which disables type checking.
// Implicit any as JSON.parse doesn't know what type of data it returns so it can be "any" thing...
const json = JSON.parse("55");
// Most expect json to be an object, but it can be a string or a number like this example
console.log(typeof json);
This behavior can be disabled by enabling noImplicitAny
as an option in a TypeScript's project tsconfig.json
. That is a JSON config file for customizing how some of TypeScript behaves.
Note: you may see primitive types capitalized like Boolean
.
boolean !== Boolean
For this tutorial just know to use the lower-cased values, the upper-case ones are for very specific circumstances.