TypeScript Types


TypeScript is a super-set of JavaScript. One reason to use TypeScript and compile those files to JavaScript is to allow TypeScript to check for data-type errors. If we define a variable as a number and then attempt to assign a string literal to it, TypeScript will give us a warning when we use the command line compiler, tsc to compile it. This error checking is very helpful when debugging any program, particularly medium or larger sized programs.

We declare a variable with var. Below we declared a variable called n and gave it a type of number and initialized the value to one. At the bottom of the block of code we then assigned the string Sammy to the variable n.

When you compile this code you get an error but you still get the JavaScript code because the compiler does not consider this error to be serious enough to refuse compilation.

TypeScript

var n : number = 1;
var whatever : any = 7;

whatever = 'John';
whatever = "Bobby";

// these are comments
// Here we are assigning a 
// string to a number n
n = "Sammy";

JavaScript

var n = 1;
var whatever = 7;
whatever = 'John';
whatever = "Bobby";
// these are comments
// Here we are assigning a 
// string to a number n
n = "Sammy";

List of TypeScript Types

  • Boolean – true or false
  • Number – all numbers are floating point numbers
  • String
  • Array – must be all of the same type, unless the type is set to any
  • Enum
  • Any
  • Void – is not really a type; equal to nothing

Examples of Declaring Variables

var isWinter : boolean = true;
var amount : number = 6;
var piename : string = "apple pie";
var users : string[] = ["Brad", "Susie", "Julie"]; // array of strings
var stuff : any[] = ["John", "Bob", "Sally", 34.2]; // array of any type
enum Starks {Bran, Catlyn, Mary};
var cat : Starks = Starks.Catlyn;
// good idea to put : string to be sure that a string type
// is returned. tsc will throw an error if not a string.
function getName() : string { // returns a string type
  return "Johnny";
  // return 1; would throw an error
}
function saySeason() : void {
  console.log("Winter has arrived");
  console.log(getName());
}
getName();
saySeason();

Below is a screen shot of the output. Here I am using Git Bash console. The file name is t2.ts. First compile it with tsc. Next, run it with Node. Node runs JavaScript, not TypeScript; the file extension must be js for Node to run it.

Series Navigation<< TypeScript InstallationTypeScript Interfaces >>

Leave a comment

Your email address will not be published. Required fields are marked *