Get Started With TypeScript in 2019

This article aims to bring you up to speed with around 95% of the scenarios you will typically encounter in a standard TypeScript project. For that last 5%, well, Google is your friend and I’ve added links to useful TypeScript resources at the bottom of the article.

Based on the Stack Overflow Developer survey in 2018, TypeScript is more “loved” as a programming language than JavaScript. The reason TypeScript is so loved amongst JavaScript developers is because adding types to JavaScript allows you to spot errors before running your code. The errors provided by the TypeScript compiler will give a good indication of how an error can be fixed. Adding types to JavaScript also allows code editors to provide some more advanced features, such as code completion, project-wide refactoring, and automatic module importing.

Results of the “most loved programming languages” survey question from the 2018 Stack Overflow Developer Survey

Learning TypeScript might seem intimidating if you come to think of it as a completely new programming language. However, TypeScript is just an added layer to JavaScript and you by no means have to know every bit of syntax that comes along with TypeScript before you can start using it. TypeScript allows you to easily convert a JavaScript file by changing the file extension from .js to .ts and all the code will compile properly as TypeScript. You can configure TypeScript to be more restrictive if you want to enforce a larger percentage of type coverage in your TypeScript files, but that can be done once you get more familiar with the language.

This article aims to bring you up to speed with around 95% of the scenariosyou will typically encounter in a standard TypeScript project. For that last 5%, well, Google is your friend and I’ve added links to useful TypeScript resources at the bottom of the article.


Setting Up TypeScript

Of course, to begin writing TypeScript that compiles correctly, a properly configured development environment is required.

1. Install the TypeScript compiler

To start off, the TypeScript compiler will need to be installed in order to convert TypeScript files into JavaScript files. To do this, TypeScript can either be installed globally (available anywhere in your file system) or locally (only available at the project level).

# NPM Installation Method

npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation

Yarn Installation Method

yarn global add typescript # Global installation
yarn add --dev typescript # Local installation

Commands to run from the command line to install TypeScript globally or locally on your computer

2. Make sure your editor is setup to support TypeScript

You’ll want to make sure your editor is properly configured to work with TypeScript. For example, you may need to install a plugin (such as atom-typescript if using the atom editor), in order to fully take advantage of TypeScript in your editor. If using VS Code, TypeScript support is built-in, so there are no extensions required 😎.

3. Create a tsconfig.json file

A tsconfig.json file is used to configure TypeScript project settings. The tsconfig.json file should be put in the project's root directory. The file allows you to configure the TypeScript compiler with different options.

You can have the tsconfig.json contain an empty JSON object if you just want to get TypeScript to work, but if you need the TypeScript compiler to behave differently (such as output transpiled JavaScript files in a specific output directory), you can read more about which settings can be configured.

Note: You can also run the tsc --init to generate a _tsconfig.json_file with some default options set for you and a bunch of other options commented out

4. Transpile TypeScript to JavaScript

In order to transpile your TypeScript code to JavaScript, the tsc command needs to be run in the terminal. Running tsc will have the TypeScript compiler search for the tsconfig.json file which will determine the project's root directory as well as which options to use when compiling the TypeScript and transpiling .ts files to .js files.

To quickly test that the setup works, you can create a test TypeScript file and then run tsc in the command line and see if a JavaScript file is generated beside the TypeScript file.

For example, this TypeScript file…

const greeting = (person: string) => {
console.log('Good day ' + person);
};

greeting('Daniel');

Example TypeScript syntax

Should transpile to this JavaScript file…

var greeting = function(person) {
console.log('Good day ' + person);
};

greeting('Daniel');

JavaScript file that gets generated from transpiling TypeScript

If you’d like for the TypeScript compiler to watch for changes in your TypeScript files and automatically trigger the transpilation of .ts to .jsfiles, you can run the tsc -p. command in your project’s repository.

In VS Code, you can use ⌘⇧B to bring up a menu that can run the transpiler in either normal or watch modes (tsc:build or tsc:watch, respectively).

The VS Code build tasks menu that can be brought up using ⌘⇧B


Understanding Static and Dynamic Types

JavaScript comes with 7 dynamic types:

  • Undefined
  • Null
  • Boolean
  • Number
  • String
  • Symbol
  • Object

The above types are called dynamic since they are used at runtime.

TypeScript brings along static types to the JavaScript language, and those types are evaluated at compile time (without having to run the code). Statictypes are what predict the value of dynamic types and this can help warn you of possible errors without having to run the code.


Basic Static Types

Alright, let’s dive into the syntax of TypeScript. What follows are the most commonly seen types in TypeScript.

Note: I’ve left out the never and object types since, in my experience, they are not very commonly used.

boolean

The simple true and false values you've come to know and love.

let isAwesome: boolean = true;

boolean type annotation

string

Textual data surrounded in either single quotes ('), double quotes ("), or back ticks.

let name: string = 'Chris';
let breed: string = 'Border Collie';

string type annotation

If using back ticks, the string is called a template literal and expressions can be interpolated within them.

let punchline: string = 'Because it was free-range.';
let joke: string = Q: Why did the chiken cross the road? A: ${punchline};

string type annotation with the use of template literals

number

Any floating point number is given the type of number. The four types of number literals that are supported as part of TypeScript are decimalbinaryoctal and hexadecimal.

let decimalNumber: number = 42;
let binaryNumber: number = 0b101010; // => 42
let octalNumber: number = 0o52; // => 42
let hexadecimalNumber: number = 0x2a; // => 42

number type annotation

Note: If the binary, octal, and hexadecimal numbers confuse you, you’re not alone.

array

Array types in TypeScript can be written in two ways. The first way requires that [] be postfixed to the type of elements that are found in the array.

let myPetFamily: string[] = ['rocket', 'fluffly', 'harry'];

array of strings using the square bracket notation

The alternative way to write Array types is to use Array followed by the type of elements that are found in the array (within angle brackets).

let myPetFamily: Array<string> = ['rocket', 'fluffly', 'harry'];

array of strings using the angle bracket notation

tuple

A tuple is an array that contains a fixed number of elements with associated types.

let myFavoriteTuple: [string, number, boolean];

myFavoriteTuple = ['chair', 20, true]; // ✅
myFavoriteTuple = [5, 20, true]; // ❌ - The first element should be a string, not a number

Declaring a tuple with 3 elements and then assigning values to the tuple

enum

An enum is a way to associate names to a constant value, which can be either a number or a string. Enums are useful when you want to have a set of distinct values that have a descriptive name associated with it.

By default, enums are assigned numbers that start at 0 and increase by 1for each member of the enum.

enum Sizes {
Small,
Medium,
Large,
}

Sizes.Small; // => 0
Sizes.Medium; // => 1
Sizes.Large; // => 2

Example of an enum starting at 9

The first value can be set to a value other than 0.

enum Sizes {
Small = 1,
Medium,
Large,
}

Sizes.Small; // => 1
Sizes.Medium; // => 2
Sizes.Large; // => 3

Example of the enum starting at a value other than 0

Enums are by default assigned numbers, however, string values can also be assigned to an enum.

enum ThemeColors {
Primary = 'primary',
Secondary = 'secondary',
Dark = 'dark',
DarkSecondary = 'darkSecondary',
}

Example of an enum with string values

any

If the type of a variable is not known and we don’t want the type checker to complain at compilation time, then the type of any can be used.

let whoKnows: any = 4; // assigned a number

whoKnows = 'a beautiful string'; // can be reassigned to a string
whoKnows = false; // can be reassigned to a boolean

Example of the any type

any will likely frequently be used when starting out with TypeScript. However, it's best to try to reduce the usage of any since the usefulness of TypeScript decreases when the compiler isn't aware of the types associated with variables.

void

When there is no type associated with something, the void type should be used. It is most commonly used when specifying the return value of a function that doesn't return anything.

const darkestPlaceOnEarth = (): void => {
console.log('Marianas Trench');
};

Example of using the void type

null and undefined

Both null and undefined correspond to the types of the null and undefined values you might see in JavaScript. These types aren't very useful when used on their own.

let anUndefinedVariable: undefined = undefined;
let aNullVariable: null = null;

Example of how the null and undefined types could be used

By default the null and undefined types are subtypes of all other types, meaning that a variable of type string can be assigned a value of null or undefined. This is often undesirable behavior and thus it’s usually recommended to set the strictNullChecks compiler option in a tsconfig.json file to true. Setting the strictNullChecks option to truemakes it so that null and undefined need to be explicitly set as a type for a variable.


Type Inference

Fortunately, you don’ have to specify types absolutely everywhere in your code because TypeScript has what is called Type Inference. Type inference is what the TypeScript compiler uses to automatically determine types.

Basic Type Inference

TypeScript can infer types during variable initialization, when default parameter values are set, and while determining function return values.

// Variable initialization
let x = 10; // x is given the number type

Example of type inference where the x variable has an inferred type of number

In the above example, x is assigned a number, TypeScript associates the xvariable with a type of number.

// Default function parameters
const tweetLength = (message = 'A default tweet') => {
return message.length;
};

An inferred type of string is given to the message parameter

In the above example, the message parameter is assigned a default value which is of type string, so therefore the TypeScript compiler infers that message is of type string and therefore doesn’t throw a compilation error when the length property is being accessed.

function add(a: number, b: number) {
return a + b;
}

const result = add(2, 4);

result.toFixed(2); // ✅
result.length; // ❌ - length is not a property of number types

An inferred type of number is assigned to the return value of the add function based on the types of the function’s parameters

In the above example, since TypeScript is told that both parameters to the add function have a type of number, it can infer that the return type will also be a number.

Best Common Type Inference

When a type is being inferred from multiple possible types, TypeScript uses a “best common type” algorithm to pick a type that works with all the other candidates.

let list = [10, 22, 4, null, 5];

list.push(6); // ✅
list.push(null); // ✅
list.push('nope'); // ❌ - type 'string' is neither of type 'number' or 'null'

The best common type algorithm determines that only number and null types should be allowed as elements to the list array

In the above example, the array is composed of both number and nulltypes, and therefore TypeScript expects only number and null values to be a part of the array.


Type Annotation

When the Type Inference system is not enough, you will need to declare types on variables and objects.

Basic Types

All the types introduced in the Basic Static Types section can be declared using a : followed by the name of the type.

let aBoolean: boolean = true;
let aNumber: number = 10;
let aString: string = 'woohoo';

Examples of annotating basic types

Arrays

As shown in the section talking about the array type, arrays can be annotated one of two ways.

// First method is using the square bracket notation
let messageArray: string[] = ['hello', 'my name is fred', 'bye'];

// Second method uses the Array keyword notation
let messageArray: Array<string> = ['hello', 'my name is fred', 'bye'];

Annotating arrays

Interfaces

One way to put together multiple type annotations is by using an interface.

interface Animal {
kind: string;
weight: number;
}

let dog: Animal;

dog = {
kind: 'mammal',
weight: 10,
}; // ✅

dog = {
kind: true,
weight: 10,
}; // ❌ - kind should be a string

Annotating types using an interface

Type Alias

To make things confusing, TypeScript also allows you to specify multiple type annotations using a type alias.

type Animal = {
kind: string;
weight: number;
};

let dog: Animal;

dog = {
kind: 'mammal',
weight: 10,
}; // ✅

dog = {
kind: true,
weight: 10,
}; // ❌ - kind should be a string

Annotating types using a type alias

What seems to be the best practice in terms of using an interface or a type alias is that you should generally just pick either interface or type in your codebase and be consistent. However, if writing a 3rd party public API that can be used by others, use an interface type.

If you want to get a more detailed comparison between the type alias and an interface, I would recommend this article by Matin Hochel.

Inline Annotations

Instead of creating a re-usable interface, it might be more appropriate to annotate a type inline instead.

let dog: {
kind: string;
weight: number;
};

dog = {
kind: 'mammal',
weight: 10,
}; // ✅

dog = {
kind: true,
weight: 10,
}; // ❌ - kind should be a string

Using an inline type annotation

Generics

There are situations where the specific type of a variable doesn’t matter, but a relationship between the types of different variables should be enforced. For those cases, generic types should be used.

const fillArray = <T>(len: number, elem: T) => {
return new Array<T>(len).fill(elem);
};

const newArray = fillArray<string>(3, 'hi'); // => ['hi', 'hi', 'hi']

newArray.push('bye'); // ✅
newArray.push(true); // ❌ - only strings can be added to the array

Using generic types to define type relationships

The above example has a generic type T that corresponds to the type of the second argument passed to the fillArray function. The second argument passed to the fillArray function is a string, and therefore the created array will have all of its elements set to have a type of string.

It should be noted that it is by convention that single letters are used for generic types (e.g. T or K). However, there is nothing stopping your from using more descriptive names for your generic types. Here is the above example with a more descriptive name for the supplied generic type:

const fillArray = <ArrayElementType>(len: number, elem: ArrayElementType) => {
return new Array<ArrayElementType>(len).fill(elem);
};

const newArray = fillArray<string>(3, 'hi'); // => ['hi', 'hi', 'hi']

newArray.push('bye'); // ✅
newArray.push(true); // ❌ - only strings can be added to the array

Using more descriptive names for generic types

Union Type

In scenarios where a type can be one of multiple types, a union type is used by separating the different type options with a |.

// The name parameter can be either a string or null
const sayHappyBirthdayOnFacebook = (name: string | null) => {
if (name === null) {
console.log('Happy birthday!');
} else {
console.log(Happy birthday ${name}!);
}
};

sayHappyBirthdayOnFacebook(null); // => "Happy birthday!"
sayHappyBirthdayOnFacebook('Jeremy'); // => "Happy birthday Jeremy!"

An example of a union type annotation

Intersection Type

An intersection type uses the & symbol to combine multiple types together. This is different than the union type, as a union type says "the resulting type is one of the listed types" whereas the intersection type says "the resulting type is the combination of all listed types".

type Student = {
id: string;
age: number;
};

type Employee = {
companyId: string;
};

let person: Student & Employee;

person.age = 21; // ✅
person.companyId = 'SP302334'; // ✅
person.id = '10033402'; // ✅
person.name = 'Henry'; // ❌ - name does not exist in Student & Employee

An example of an intersection type annotation

Tuple Type

Tuples are annotated using a : followed by a comma separated list of types within square brackets.

let list: [string, string, number];

list = ['apple', 'banana', 8.75]; // ✅
list = ['apple', true, 8.75]; // ❌ - the second argument should be of type string
list = ['apple', 'banana', 10.33, 3]; // ❌ - the tuple specifies a length of 3, not 4

Annotating a variable using a tuple type

Optional Types

There may be instances where a function parameter or object property is optional. In those cases, a ? is used to denote these optional values.

// Optional function parameter
function callMom(message?: string) {
if (!message) {
console.log('Hi mom. Love you. Bye.');
} else {
console.log(message);
}
}

// Interface describing an object containing an optional property
interface Person {
name: string;
age: number;
favoriteColor?: string; // This property is optional
}

Defining optional types


Useful Resources

For the parts of TypeScript that weren’t covered in this article, I recommend the following resources.


TypeScript Handbook (Official TypeScript docs)

TypeScript Deep Dive (Online TypeScript Guide)

Understanding TypeScript’s Type Annotation (Great introductory TypeScript article)


By :Robert Cooper

Introduction Boolean in JavaScript and TypeScript

Introduction Boolean in JavaScript and TypeScript

Boolean values are supported by both JavaScript and TypeScript and stored as true/false values .This is because, while JavaScript coerces an object to its primitive type, the TypeScript type system does not. TypeScript treats it like an object type.

Boolean in JavaScript

boolean can take the values of true and false. Values from other types can be truthy or falsy, like undefined or null.

let b = true
if(b) console.log('logged')

b = false
if(b) console.log('not logged')

b = undefined
if(b) console.log('not logged')

b = null
if(b) console.log('not logged')

Values other than undefined, null or false considered falsy are "" (empty string), -0 and 0, as well as NaN.

To get the boolean value of any value, you can use the Boolean function:

Boolean(false) // false
Boolean(true) // true
Boolean("false") // true ❗️
Boolean("Hey folks") // true
Boolean({}) // true
Boolean([]) // true
Boolean(123.4) // true
Boolean(Symbol()) // true
Boolean(function() {}) // true
Boolean(undefined) // false
Boolean(null) // false
Boolean(NaN) // false
Boolean(0) // false
Boolean("") // false

Rule of thumb: All empty values evaluate to false. Empty object {} and empty array [] (which is an object itself) do have value as they are containers for other values.

The Boolean function is really good to filter empty values from collections:

const collection = [
  { name: 'Stefan Baumgartner', age: 37 },
  undefined,
  { name: 'D.', age: 36 },
  false
  { name: 'C.', age: 2},
  false
]

collection.filter(Boolean) // handy!

Together with Number – which converts all values into their number counterpart or NaN, this is a really cool way of getting to actual values quickly:

const x = ["1.23", 2137123, "wut", false, "lol", undefined, null]
  .map(Number)
  .filter(Boolean) // [1.23, 2137123] 👍

Boolean exists as a constructor and has the same conversion rules as the Boolean function. However, with new Boolean(...) you create a wrapping object, making value comparisions truthy, but reference comparisions falsy:

const value = Boolean("Stefan") // true
const reference = new Boolean("Stefan") // [Boolean: true]

value == reference // true
value === reference // false

You get to the value via .valueOf():

value === reference.valueOf() // true

I have a REPL for you to check. The use of Boolean as a function is obviously great, but new Boolean has very limited use. If you know a practical use case, please let me know.

Boolean in TypeScript

boolean in TypeScript is a primitive type. Be sure to use the lower case version and don’t refer to
object instances from Boolean

const boolLiteral: boolean = false // 👍
const boolObject: Boolean = false // 👎

It works, but it’s bad practice as we really rarely need new Boolean objects.

You can assign true, false and undefined and null to boolean in TypeScript without strict null checks.

const boolTrue: boolean = true // 👍
const boolFalse: boolean = false // 👍
const boolUndefined: boolean = undefined // 👍
const boolNull: boolean = null // 👍

With that, boolean is the only one we can express fully through union types:

type MyBoolean = true | false | null | undefined // same as boolean

const mybool: MyBoolean = true
const yourbool: boolean = false

When we enable the strictNullChecks compiler flag, the set of values reduces to true and false.

const boolTrue: boolean = true // 👍
const boolFalse: boolean = false // 👍
const boolUndefined: boolean = undefined // 💥
const boolNull: boolean = null // 💥

So our set reduces to two values in total.

type MyStrictBoolean = true | false

We can also get rid of null values with the NonNullable helper type:

type NonNullable<T> = T extends null | undefined
  ? never
  : T;

type MyStrictBoolean = NonNullable<MyBoolean> // true | false

The fact that boolean consists of a limited set of values only used in conditions, allows for interesting conditional types.

Think of an mutation in a datastore through a function. You set a flag in a function that updates e.g. the user id. You have to provide the user ID then:

type CheckUserId<Properties, AddUserId> = 
    AddUserId extends true 
    ? Properties & { userId: string }
    : Properties & { userId?: string }

Depending on the value of our generic AddUserId, we expect the property userId to be set or to be optional.

We can make this type more explicit by extending our generics from the types we expect

- type CheckUserId<Properties, AddUserId> = 
+ type CheckuserId<
+  Properties extends {},
+  AddUserId extends boolean
+ >
     AddUserId extends true 
     ? Properties & { userId: string }
     : Properties & { userId?: string }

In use, it might declare a function like this:

declare function mutate<P, A extends boolean = false>
  (props: CheckUserId<P, A>, addUserId?: A): void

Note that I even set a default value for A to make sure CheckUserId gives the correct info depending on addUserId to be set or not.

The function in action:

mutate({}) // 👍
mutate({ data: 'Hello folks' }) // 👍
mutate({ name: 'Stefan' }, false) // 👍
mutate({ name: 'Stefan' }, true) // 💥 userId is missing
mutate({ name: 'Stefan', userId: 'asdf' }, true) // 👍 userId is here

Handy if your code relies a lot on truthy and falsy values. As always, there’s playground for you.

Originally published at fettblog.eu on 10 September 2019

Understanding void in JavaScript and TypeScript

Understanding void in JavaScript and TypeScript

void exists in both JavaScript as an operator and in TypeScript as a primitive type. And in both worlds void works a little bit different than most people are used to.

If you come from traditional, strongly typed languages you might be familiar with the concept of void: A type telling you that functions and methods return nothing when called.

void in JavaScript

void in JavaScript is an operator which evaluates the expression next to it. No matter which expression is evaluated, void always returns undefined.

let i = void 2; // i === undefined

Why would we need something like this? First, in earlier times, people were able to override undefined and giving it an actual value. void always returned the real undefined.

Second, it’s a nice way to call immediately invoked functions:

void function() {
  console.log('What')
}()

All without polluting the global namespace:

void function aRecursion(i) {
  if(i > 0) {
    console.log(i--)
    aRecursion(i)
  }
}(3)

console.log(typeof aRecursion) // undefined

Since void always returns undefined, and void always evaluates the expression next to it, you have a very terse way of returning from a function without returning a value, but still calling a callback for example:

// returning something else than undefined would crash the app
function middleware(nextCallback) {
  if(conditionApplies()) {
    return void nextCallback();
  }
}

Which brings me to the most important use case of void: It’s a security gate for your app. When your function is always supposed to return undefined, you can make sure that this is always the case.

button.onclick = () => void doSomething();

void in TypeScript

void in TypeScript is a subtype of undefined. Functions in JavaScript always return something. Either it’s a value, or undefined

function iHaveNoReturnValue(i) {
  console.log(i)
} // returns undefined

Since functions without a return value always return undefined, and void always returns undefined in JavaScript, void in TypeScript is a proper type for telling developers that this function returns undefined:

declare function iHaveNoReturnValue(i: number): void

void as type can also be used for parameters and all other declarations. The only value that can be passed is undefined:

declare function iTakeNoParameters(x: void): void

iTakeNoParameters() // 👍
iTakeNoParameters(undefined) // 👍
iTakeNoParameters(void 2) // 👍

So void and undefined are pretty much the same. There’s one little difference though, and this difference is significant: void as a return type can be substituted with different types, to allow for advanced callback patterns:

function doSomething(callback: () => void) {
  let c = callback() // at this position, callback always returns undefined
  //c is also of type undefiend
}

// this function returns a number
function aNumberCallback(): number {
  return 2;
}

// works 👍 type safety is ensured in doSometing
doSomething(aNumberCallback) 

This is desired behaviour and often used in JavaScript applications. Read more on this pattern called substitutability in my other articles.

If you want to make sure to pass functions who only return undefined (as in “nothing”), be sure to adapt your callback method signature:

- function doSomething(callback: () => void) {
+ function doSomething(callback: () => undefined) { /* ... */ }

function aNumberCallback(): number { return 2; }

// 💥 types don't match
doSomething(aNumberCallback)

You’ll propably be good with void most of the time.

Originally published at fettblog.eu on 06 September 2019

JavaScript vs Typescript: What's the Difference?

JavaScript vs Typescript: What's the Difference?

For a Developer, It's very important to decide which language he should use to develop an application with a specific requirement. In this post, you'll see the difference between JavaScript and Typescript, from which you choose the language that's right for you.

Originally published at https://www.guru99.com/
JavaScript vs Typescript: What's the Difference?

In this tutorial, you will learn

  • What is JavaScript?
  • What is Typescript?
  • Why JavaScript?
  • Why Typescript?
  • History of Javascript
  • History of Typescript
  • Features of Javascript
  • Features of Typescript
  • Typescript vs. JavaScript
  • What is better?
What is JavaScript?

JavaScript is a scripting language which helps you create interactive web pages. It followed rules of client-side programming, so it runs in the user's web browser without the need of any resources forms the web server. You can also use Javascript with other technologies like REST APIs, XML, and more.

The idea behind developing this script is to make it a complementary scripting language like Visual Basic was to C++ in Microsoft's language families. However, JavaScript is not designed for large complex applications. It was developed for applications with a few hundred lines of code!

What is Typescript?

Typescript is a modern age Javascript development language. It is a statically compiled language to write clear and simple Javascript code. It can be run on Node js or any browser which supports ECMAScript 3 or newer versions.

Typescript provides optional static typing, classes, and interface. For a large JavaScript project adopting Typescript can bring you more robust software and easily deployable with a regular JavaScript application

Why JavaScript?
  • Open source project with Microsoft's patronage
  • Specially designed tool for small scripts
  • Supports classes, interfaces & modules.
  • Compiled JavaScript runs in any browser
  • Allows cross-compilation
  • You can extend JavaScript for writing large apps
  • Adds support for classes, interfaces, and modules
Why Typescript?
  • TypeScript supports JS libraries & API Documentation
  • It is a superset of Javascript
  • It is optionally typed scripting language
  • TypeScript Code can be converted into plain JavaScript Code
  • Better code structuring and object-oriented programming techniques
  • Allows better development time tool support
  • It can extend the language beyond the standard decorators, async/await
History of Javascript

Netscape Communications Corporation programmer Brendan Eich created Javascript. It was meant to working Netscape navigator. However, after becoming a popular scripting tool, it is had become LiveScript. Later on, it was renamed as JavaScript to reflect Netscape's support of Java within its browser.

Let see an important landmark in the history of Javascript:

  • It was launched in September 1995, and It took just ten days to develop this e scripting language which was initially called Mocha
  • In November 1996, Netscape submitted JavaScript to ECMA (European Computer Manufacturers Association) International
  • ECMAScript 2 was released in 1998
  • ECMAScript 3 was released in 1999
  • In 2005, Eich and Mozilla join ECMA to develop E4X Java script
  • In January 2009, the CommonJS project was launched with the aim of defining a common standard library
  • In June 2011, ECMAScript 5.1 was released
  • In June 2015. ECMAScript 2016 was released
  • The current version is ECMAScript 2017 which was released in June 2017
History of Typescript

Let see important landmarks from the History of Typescript:

  • The typescript was first made public in the year 2012
  • After two years of internal development at Microsoft. TypeScript 0.9, released in 2013
  • Additional support for generics TypeScript 1.0 was released at Build 2014
  • In July 2014, a new TypeScript compiler came which is five times faster then it's previous version
  • In July 2015, support for ES6 modules, namespace keyword, for, of support, decorators
  • In November 2016, an added feature like key and lookup types mapped types, and rest
  • On March 27, 2018, conditional types, the improved key with intersection types supports added in the Typescript.
Features of Javascript
  • It's a cross-platform language
  • It's used for client side and server side
  • It's easy to learn and to start with
  • It's a dynamic language: flexible and powerful
  • You have 'the great freedom' to do whatever you want with any object
  • Strong Testing Workflow
  • Added Dependencies
  • Framework Unsupported
Features of Typescript
  • Maintainability
  • Offered great productivity for developers
  • Code navigation and bug prevention
  • Code 'discoverability' & refactoring
  • Optional Static Type Annotation / Static Typing
  • Additional Features for Functions
  • Supports ES6
  • Supports interfaces, sub-interfaces, classes, and subclasses
  • Scalable HTML5 client-side development
  • Rich IDE available with autocomplete and code navigation features.
  • Class-based object-oriented with the inheritance of private members and interfaces.
JavaScript vs Typescript

What is better?

In the end, we can say that if an experienced developer is working on relatively small coding projects, then JavaScript is ideal. However, if you have knowledge and expertise development team, then Typescript is a most preferred option. 

Summary
  • JavaScript is a scripting language which helps you create interactive web pages
  • Typescript is a modern age Javascript development language
  • Javascript is a specially designed tool for small scripts
  • TypeScript supports JS libraries & API Documentation
  • Javascript first version was published in the year 1995
  • The typescript was first made public in the year 2012
  • It's used for client side and server side
  • Typescript offered great productivity for developers
  • Javascript is a Lightweight, interpreted, object-oriented language with first-class functions
  • Typescript is a powerful type system, including generics & JS features
  • For small size project Javascript is an ideal option, but for large size project you can use Typescript 

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading 

JavaScript Basics Before You Learn React

Build a CMS with Laravel and Vue

Google’s Go Essentials For Node.js / JavaScript Developers

From Javascript to Typescript to Elm

Creating a Modal Dialog in Angular 8 with TypeScript