Category Archives: Typescript

WHAT’S NEW IN TYPESCRIPT 2.6

What’s New in TypeScript 2.6

New in TypeScript 2.6

Microsoft’s TypeScript language is an added superset of JavaScript, designed to handle the needs of challenging programs worked on by there teams.

Microsoft’s TypeScript language is an added superset of JavaScript, designed to handle the needs of challenging programs worked on by there teams.

WHAT’S NEXT IN TYPESCRIPT 2.7?

TypeScript 2.7 is due in January 2018 and will feature improved type inference for object literals. The major reason for this upgrade to support both the JSX fragment syntax and properties named with const- declared symbols. An increased builder compiler API is also planned.

At some point perhaps beyond TypeScript 2.7, the language is slated to support project references and provision of specific types of variadic functions.

WHAT’S NEW IN THE CURRENT VERSION TYPESCRIPT 2.6?

TypeScript 2.6 is presented as a strict mode flag, which is identified as strictFunctionTypes. In strict mode, any function type that does not originate from a method has its parameters compared as contravariant. TypeScript usually compared as a parameter in a “bivariant” manner, allowing for benefits such as a simpler model for working with arrays. TypeScript 2.6 offers an increasing strictness on all function types except methods.

ERROR SUPPRESSION COMMENTS WITH // @TS-IGNORE:

Traditionally, we have avoided error suppression within TypeScript because in most cases the users asked for it could be solved through more accurate declaration files, or using a type assertion to any.

For the prior one, the benefits are obvious: the developer wants to start moving over to TypeScript, but he/she has to run into a pattern that is particularly difficult to model. The developer might spend time trying to understand it, but maybe he/she would rather get rid of it later on anyway, so to just avoid errors because the code will still run fine.

The latter situation is a bit less clear. The impetus here was that within some large companies, dependencies across projects are updated in tandem, including TypeScript itself and @types declaration files from Definitely Typed. If any change is done the developer gets a type-checking error, someone has to fix that to elude the breaking build. But now a question arises: Who can do this?

The TypeScript 2.6 is bringing // @ts-ignore comments to TypeScript files. These comments suppress any errors that occur on the next line. For instance, in the following code, TypeScript would ordinarily report an error about the console.log statement being unreachable. In TypeScript 2.6, the // @ts-ignore comment flattens the error entirely.

if (false) {

// @ts-ignore: Unreachable code error

console.log(“hello”);

}

BREAKING CHANGES AND DEPRECATIONS

There are several minor changes that may impact the codebase.

Write only references are now considered unused under — noUnusedLocals and –noUnusedParameters.

In ambient contexts such as declaration files, and declare module blocks, expressions are now rejected in defaultexports.

Uninhabitable types resulting from intersections will simplify to never when placed in a union.

Various changes have been made to DOM declarations in lib.d.ts.

TYPESCRIPT 2.4 RC

TypeScript 2.4 RC

TypeScript 2.4 RC

Version 2.4 of TypeScript, a popular, type superset of JavaScript. It offers improved load times with the addition of a dynamic import expressions capability. A release candidate version is now available via NuGet or via NPM. Explore this article and see what’s new in TypeScript 2.4 RC.

 

The latest stable version of TypeScript, can be grabbed through NuGet, or use the following command with npm:

npm install -g typescript@rc

Visual Studio 2015 users (who have Update 3) can install TypeScript from here, and Visual Studio 2017 users using Update 2 will be able to get TypeScript by simply installing it from here.

To get it working, user can easily configure Visual Studio Code and Sublime Text plugin to pick up whatever version the user needs.

DYNAMIC IMPORT EXPRESSIONS

Dynamic import expressions is a new feature and part of ECMAScript that allows the users to asynchronously load a module at any arbitrary point in their program.

For instance, imagine a webpage that allows the user to create and edit images. When the user is working on one file, the page will allow the user to download that file immediately; but if he/she is working on multiple images, then the user can save all of them as a .zip file.

User can conditionally import other modules and libraries. For example, here’s an async function that only imports a utility library when it’s needed:

async function getZipFile(name: string, files: File[]): Promise {
const zipUtil = await import(‘./utils/create-zip-file’);
const zipContents = await zipUtil.getContentAsBlob(files);
return new File(zipContents, name);
}

Many bundlers have support for automatically splitting output bundles based on these import expressions, so consider using this new feature with the esnext module target.

STRING ENUMS
TypeScript 2.4 now allows enum members to contain string initializers.
enum Colors {
Red = “RED”,
Green = “GREEN”,
Blue = “BLUE”,
}

The limitation is that string-initialized enums cannot be reverse-mapped to get the original enum member name. In other words, the user cannot write Colors[“RED”] to get the string “Red”. Improved inference for generics

TypeScript 2.4 introduces a few wonderful changes around the way generics are inferred.

RETURN TYPES AS INFERENCE TARGETS:

TypeScript can now make inferences for the return type of a call. This can improve user experience and catch errors.

function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[] {
return a => a.map(f);
}
const lengths: (a: string[]) => number[] = arrayMap(s => s.length);
As an example of new errors you might spot as a result:
let x: Promise = new Promise(resolve => {
resolve(10);
// ~~ Error!
});

STRICTER CHECKING FOR GENERIC FUNCTIONS

TypeScript now tries to unify type parameters when comparing two single-signature types. As a result, user gets the stricter checks when relating two generic signatures.

Type A = <T, U>(x: T, y: U) => [T, U];
type B = <S>(x: S, y: S) => [S, S];
function f(a: A, b: B) {
a = b;  // Error
b = a;  // Ok
}

WEAK TYPE DETECTION

TypeScript 2.4 introduces the concept of “weak types”. Any type that contains nothing but a set of all-optional properties is considered to be weak. For example, this Options type is a weak type:

interface Options {
data?: string,
timeout?: number,
maxRetries?: number,}
In TypeScript 2.4, it’s now an error to assign anything to a weak type when there’s no overlap in properties. For example:
function sendMessage(options: Options) {
// …
}
const opts = {
payload: “hello world!”,
retryOnFail: true,
}
// Error!
sendMessage(opts);
// No overlap between the type of ‘opts’ and ‘Options’ itself.
// Maybe we meant to use ‘data’/’maxRetries’ instead of ‘payload’/’retryOnFail’.

User can think of this as TypeScript “toughening up” the weak guarantees of these types to catch the silent bugs.

HOW DO I IMPORT OTHER TYPESCRIPT FILES?

How do I import other Typescript files?

We can use the reference tag to get the external inference of the file
Ex. export interface Animal {
name(): void;
}

export class Elephant implements Animal {

constructor() {

}

public name() {
console.log(“Elephant”);
}
}

export class Horse implements Animal {

constructor() {

}

public name() {
console.log(“Horse”);
}
}

import animals = require(“animals”)

module AnimalPanel {

var animal = new animals.Elephant();
animal.name();
}

WHY IS THE “EXPORT” KEYWORD USED TO MAKE CLASSES AND INTERFACES PUBLIC IN TYPESCRIPT?

Why is the “export” keyword used to make classes and interfaces public in Typescript?


Eg:
module some.namespace.here
{
export class SomeClass{..}
}
Is used as: varsomeVar = new some.namespace.here.SomeClass();
Solution:With the export keyword, the JavaScript adds a line to add the exported item to the module. Like in example: here.SomeClass = SomeClass;
So, visibility as controlled by public and private is just for tooling, whereas the export keyword changes the output.
In Typescript, marking a class member as public or private has no effect on the generated JavaScript. It is simple a design / compile time tool that you can use to stop your Typescript code accessing things it shouldn’t.

What’s this Typescript all About?

What’s this Typescript all About?

If you’re a Java programmer, you’ve probably heard of Typescript. But, what exactly is TypeScript?

Most web JavaScript developers will tell you that it’s a programming language that is strictly a superset of JavaScript. It provides JavaScript users with the added advantage of optional static typing and class-based object-oriented programming.

It is basically a compiled version of native JavaScript that runs without the support of a dedicated runtime library. It is designed and developed by Microsoft.

Overview

With the introduction of an optional typing system, TypeScript attempts to incorporate the advantages of a statically typed language into the dynamic world of JavaScript. Some of these benefits will include:

Type Script

  1. Accuracy with Type Checkers: Getting a platform that makes it easier for developers to create an accurate and predictable code that will eliminate common errors such as typos or incorrect value-type assumptions. Such errors are detected during the compile stage by type checkers.
  2. Seamless IDE Integration: With the information of types, an IDE can become more productive by providing useful features such auto-complete. It is open source, but you only get the clever Intellisense as you type if you use Microsoft’s Visual Studio.
  3. It is now possible to perform code refactoring operations like renaming functions or variables automatically and safely.

TypeScript vs JavaScript
Type Script is JavaScript with high level language features

TypeScript vs JavaScript
Classes

In relation to its structuring mechanism, TypeScript introduces the concept of a class-based object-oriented programming, making it much easier to structure code into classes, create a class hierarchy and manage the visibility of data throughout a system.

But in the JavaScript code, private members are publicly accessible. However, it is possible to hide methods and variables within JavaScript by placing them within a constructor function and making them accessible to the class internals through a closure.

Modules

TypeScript uses the concept of internal and external modules.

In the case of JavaScript, every variable/- function that isn’t defined in a function is created in a global scope. Variables defined without a “var” keyword will also be created. Cluttering the global namespace will cause naming conflicts. If this happens, variables or functions in the global scope will override existing ones with the same name and can create some untraceable errors.

TypeScript’s internal modules follow the same structure as namespaces as they allow defining of symbols like variables classes and the global scope. External modules are how TypeScript defines asynchronous loaded modules for either node.js or require.js module-loadingsystems.TypeScript also employs the use of a module to declare the application program interfaces that third-party libraries expose.

TypeScript Benefits

Here are some benefits that make Type- Script a prominent language:

  • A platform for safe and automatic refactoring.
  • High-visibility APIs and type declaration code contracts.
  • Easy error detection during compilation.
  • Class-based object orientation, with private members and an interface module support.
  • Easy interoperability of JavaScript code.
  • It allows you to convert any JavaScript code into a valid TypeScript code.
  • There is low or no risk in trying Type- Script since it can be removed as easily as it was installed.

The best part about TypeScript is that it allows you to begin with a JavaScript code and eventually add type annotations.

TypeScript Cons

Although TypeScript comes with loads of features and advantages, TypeScript also has its fair share of cons and limitations. So here are a few drawbacks of Type- Script compared to JavaScript:

      • To obtain the most out of TypeScript, developers are required to employ the use the type annotations at every point of their code, making such a dynamic language seem tedious and cumbersome. So, you’re going to have to devote plenitude of focus and effort while writing a strongly-typed JavaScript code.
    • Although the TypeScript system is way more flexible than what one typically finds among mainstream languages, it is still nowhere as flexible as the JavaScript language itself. In fact, JavaScript extends itself to a strong deal for TypeScript since it imposes a strongly-typed language system to make it easier to use with JavaScript, which is intrinsically dynamic.
  • Not all JavaScript patterns are 100% compatible with TypeScript. In fact, many commonly used JavaScript patterns can be difficult or impossible to use in Typescript. And although developers are working to create a smoother integration, it will take a couple of years to reach that point.

Why to use TypeScript:

Transparency:

TypeScript is a language that generates plain JavaScript files. The code produced follows all the JavaScript rules (the “good parts”) and thus is clean and modular (one file per class). You can export namespaces (modules) and to be honest most of the time the produced JavaScript is fairly the same as what we can do.

Developer Reach:

Furthermore, we can reach more users who can be afraid by JavaScript. Type-Script is for instance a good way for C#, Java and all strong typed languages developers to start developing for the web.

It technically boils down to its usage, for example, using TypeScript is much more advantageous for medium-large scale projects, but might not make as much sense for smaller projects.

Example:

As an example, here’s some Typescript (you can play with this in the Typescript Playground) and the Javascript code that it would produce.

Notice how the Typescript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

typescript vs javascript

It is by no means an improved version of JavaScript, nor a complete replacement for the same. In fact, in order to use and make the most out of TypeScript, a developer or development team will need to be fairly well-versed with TypeScript as well as JavaScript.