Category Archives: TypeScript

How to handle async functions inside constructors in TypeScript

In this post we will discuss some options you have with calling async functions in constructor of your TypeScript classes.

So, first of all – why would you do this? Well, maybe you need some data from a web API to fill the object with data, or you need some input from user, or some API in code from a colleague is async. Reasons may vary, but the problem is still the same :
in TypeScript, you can’t have await statement in constructor, because constructor returns instance of object, not Promise<yourObjectType>. (All of this indeed is tied to current version of TypeScript 2.2. maybe in future with native async/await keywords in JS, things will change).

So, possible solutions depend on what happens in your async functions and if you need results from this call / calls at the time you return the object.

Solutions :

1. Try to avoid async stuff in constructor. As said earlier, constructor is a function, that should initiate the object in some way and return it immediately, not return a promise that has to be awaited. That is considered a bad practice and TypeScript doesn’t allow this. More on this problem here

http://stackoverflow.com/questions/11856778/asynchronous-constructor

http://stackoverflow.com/questions/24398699/is-it-bad-practice-to-have-a-constructor-function-return-a-promise

http://stackoverflow.com/questions/36363278/does-async-await-will-allow-us-to-be-used-on-constructors

So in some sense, need for async stuff in your constructor might be considered code smell, you are doing too much in constructor. Refactor your code.

2. If you want your async code to stay in constructor for some reason, do you need results from async calls? If not and you want to call them and let them just execute, you might consider calling async functions without await. In this way you will unfortunately be unable to receive (await) the result from these calls (values passed back via resolve).
Please note, that this might result in some non deterministic issues because of how JS handles async code and I really don’t recommend this. Also another downside is, that if you would wrap everything inside constructor with try, promises that would be rejected (analogy with throwing exception in async sense will be not caught but become unhandled exceptions).

Your constructor might then look like this :

class SomeClass1 {
  constructor() {
    getConfirmAsync("1 - 1");
    getConfirmAsync("1 - 2");
    getConfirmAsync("1 - 3");
  }
}

Sample with try/catch block might look like this :

class SomeClass2 {
  constructor() {
   try {
     delayAsync(3000);
     delayAsync(2000);
     delayAsync(1000);
   } catch (e) {
     console.log(e);
   }
  }
}

No awaits means that code will continue to run and your constructor will finish and hand over new instance of your class sooner than code triggered from constructor will finish its execution. Scary, right? Don’t do it!!!!

Another take on this same approach is to leave an async self executing function in constructor like this :

class SomeClass3 {
  constructor() {
    console.log("SomeClass3 - entry");
      (async () => {
        try {
          await delayAsync(3000);
          await delayAsync(1000);
          await delayAsync(2000);
        } catch (e) {
          console.log(`catch triggered with exception ${e}`);
        }
      })();
      console.log("SomeClass3 - exit");
  }
}

Again, object would return from constructor but it would still lack calls to all async functions but this time, with proper async function, await and try/catch will work. So if for some reason first function would throw, all the others will not be hit (you can try to change the first call from 3000 to 2999 and see the results). Again, this is not recommended!

3. Simple “factory” function :

This is a way you might potentially want to go because it’s the safest one. All calls will be awaited and instance of you class will be in the state it should be.
All logic from constructor would have to be removed and stored in function that will have the logic of preparing object to the right shape. But, it is OK to separate the logic of creation from class to different function/files that knows what to do to make the object “right”?
Also you might want for safety reasons to “hide” somehow the class itself to prevent from instantiation without the factory function.
This could be done by exporting (from module) only interface of the object and “factory” function and not the class itself. Downside is, that all functions that are called in “factory” function need to be also public because “factory” function is not inside the class itself, but it is a separate function.

//exporting interface so we can work with the object outside
export interface ISomeClass {
	stringPublic: string;
	numberPublic: number;
}
 
//not exported = not visible
class SomeClass implements ISomeClass {
	public stringPublic: string;
	public numberPublic: number;
 
	private somePrivateFn() {
		console.log("this is private fn");
	}
}
 
export async function createSomeClassAsync(): Promise<SomeClass> {
	let res = new SomeClass();
 
	await delayAsync(1000);
	await getConfirmAsync("1");
	await delayAsync(3000);
	await getConfirmAsync("2");
	await delayAsync(2000);
	res.numberPublic = 1;
	res.stringPublic = "aa";
	// res.somePrivateFn(); since we are not inside function this would fail
 
	return res;
}

This is TS that has export and import statements, but in my examples on GitHub I have this implemented without export and import. I can make a sample for you that is using modules (like the one above) but I decides to cut complexity for my readers and not use any bundling tool like webpack or browserify (I recommend webpack over browserify but that is just a matter of taste).
5. You want to hook a browser event inside the constructor , like some ready event or some other that will trigger some async functions once it happened.

Your constructor might look like this :

function ready(fn) {
    if (document.readyState !== "loading") {
        fn();
    } else {
        document.addEventListener("DOMContentLoaded", fn);
    }
}

class SomeClass {
    constructor() {
        console.log("SomeClass5 - entry");
        ready(async () => {
            try {
                await delayAsync(3000);
                await delayAsync(1000);
                await delayAsync(2000);
            } catch (e) {
                console.log(`catch triggered with exception ${e}`);
            }
        });
        console.log("SomeClass5 - exit");
    }
}

I am using a helper function from http://youmightnotneedjquery.com/ to avoid adding jQ to the project, but you get the point.

If my samples doesn’t make sense for you, please to to my GitHub repo, you can find all the code I made as examples can be found there : https://github.com/rostacik/asyncTsCtorSolutions .

If  you have TypeScript installed as global npm package, just type

tsc

in the root. If you dont have TypeScript installed, you just need to do to install npm packages :

npm install

and run TypeScript compiler to build all .ts files :

 "node_modules/.bin/tsc.cmd"

Feel free to ask or discuss in the comments 🙂

How to filter particular TypeScript errors in build result

Hi interwebz.
I just want to share this short poor man’s fix when migrating TypeScript to filter out some particular errors in TypeScript build.

Why the hell you (might) need it?

So what would be the common use case , why to bother mask/mute errors on build? Compile is the first test our code need to undergo, like first pass of “unit tests”.

Our situation : currently we have a lot of .js files that let’s say most of the time worked and we need to iterate on way to migrate fully from JavaScript only to TypeScript only. So we rename .js to .ts and then we ran into errors like (among others) :

  1. error TS2365 Operator ‘>=’ cannot be applied to types ‘string’ and ‘number’.
  2. error TS2365 Operator ‘==’ cannot be applied to types ‘string’ and ‘number’.
  3.  error TS2345 Argument of type ‘number’ is not assignable to parameter of type ‘string’.

Yes indeed these are against the “logic” of TypeScript – bring types to JavaScript. But I know I want it there for some short timespan. Just to test. I don’t want to wade through 1500 same errors I know I will have to fix, but among them TypeScript also tells me big and real problems, but buried under many same errors about types.

We are not alone in this, more ppl write about it here :
https://github.com/Microsoft/TypeScript/issues/6114

https://github.com/Microsoft/TypeScript/issues/4094

https://github.com/Microsoft/TypeScript/issues/9448

and also here https://github.com/Microsoft/TypeScript/issues/11051

Solution :

So the solutions vary from custom branch of TypeScript as such to stupid grep on the command line output. And since I am on Windows 10 (my dev box) , I chose to stick with PowerShell so this is snippet that should do the job.

Lets say we want to mute TS2365 and TS2345 errors and your TS build gulp task has name someTSBuildTaskName.

PS script – output to some file :

node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345" | Out-File "grepts.txt"

PS script – output just to console (just drop the last part after pipe) :

node .\node_modules\gulp\bin\gulp.js someTSBuildTaskName --color | Select-String -NotMatch "TS2365" | Select-String -NotMatch "TS2345"

PS: I am calling here the gulp task without gulp installed with -g flag (global) so you can just call

gulp someTSBuildTaskName

with globally installed gulp and you are also good to go.

Found any better solution? Pls let us know in comments! 🙂

AD: you can also use this console log parser on Jenkins:

Regular Expression :

([\w\\\.]+)\((\d+),\d+\):\s+\w+\s+((?!TS2365|TS2345)\w+):\s+(.*)$

Mapping Script :

import hudson.plugins.warnings.parser.Warning

String fileName = matcher.group(1)
String line = matcher.group(2)
String category = matcher.group(3)
String message = matcher.group(4)

return new Warning(fileName, Integer.parseInt(line), "TS Error", category, message);

and plug this into your build pipeline.

Using typescript@next nightly package? Don’t rely on –save-dev to be up-to-date!

Just a small update for all you cutting edge TypeScript users.

If you are using typescript@next NPM package as showed here : http://blogs.msdn.com/b/typescript/archive/2015/07/27/introducing-typescript-nightlies.aspx you may run into the same issue as we did @ work.

If you would install TypeScript nightly as blog says like this (I modified the command, this will install typescript@next package locally and save dependency in devDependencies):

npm install typescript@next --save-dev

you would see something like this in your package.json (please note the date 20150818 suffix)

{
"devDependencies": {  "typescript": "^1.6.0-dev.20150818"  }
}

Which is OK, and also

npm update

will work, until TypeScript recently updated to version 1.7.0 which will update you to latest 1.6.0 verions, which is typescript@1.6.0-dev.20150825.

If you would delete the folder with TypeScript in node_modules and also entry in package.json and reinstall typescript@next package, then you would have this entry in package.json (if installed on 1.9.2015) :

{
"devDependencies": {  "typescript": "^1.7.0-dev.20150901"  }
}

which will again work until TS updated to 1.8.0. You can try to npm update with this file, you will be updated to latest 1.7.0.

So, what can we do about this? You might try this small “hack” :

{
"devDependencies": {  "typescript": "next"  }
}

Happy npm update-ing 😉

How to exclude some files from TypeScript build

If you are using TypeScript nightly (and only with TypeScript 1.6 up) you can use in your tsconfig.json new property exclude which will mostly be used for node_modules like this

(more on this here : http://blogs.msdn.com/b/typescript/archive/2015/07/27/introducing-typescript-nightlies.aspx)

:

{
   "compilerOptions": {
   "out": "../../built/local/tsc.js",
   "sourceMap": true
   },
   "exclude": [
      "node_modules"
   ]
}

More on exclude property here : https://github.com/Microsoft/TypeScript/issues/3043

How to disable building of TypeScript files in Visual Studio 2015

If you would like to disable building TypeScript files in your solution for some reason (you want different build workflow, you just work on .cs files and don’t touch .ts files), you had to search for some kind of ifs or comments out to the project file in previous version of Visual Studio.

The problem as such is not new and solution was requested for some time from TypeScript team.

After digging in some articles I found this not much hyped solution :
add node

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>

to the first

<PropertyGroup>

element in .csproj file.

For me, it worked.

More on the problem here :
https://github.com/Microsoft/TypeScript/issues/2326
https://github.com/Microsoft/TypeScript/issues/2294

One small note : if you have an error in the .ts files and compilation is disabled, build will not fail in Visual Studio 2015. But you can still see all errors in Error list tab. And you will still have IntelliSense.

In TypeScript when checking for types at runtime, don’t use type HTMLTableDataCellElement but HTMLTableCellElement

tl;dr
Type HTMLTableDataCellElement is not defined in Chrome and FireFox, this object is IE only. If you want to test at runtime for TD element in all latest browsers, use HTMLTableCellElement instead.

The whole story :

Today I ran into one subtle thing when checking for types at runtime (I made a small post about checks already here : http://rostacik.net/2015/05/27/how-to-get-type-of-object-in-typescript-when-using-union-types-and-type-guards-for-multiple-types-of-function-parameter-or-variable/). TypeScript by default gives you type hints from file that comes with it – lib.d.ts. So this row :

createElement(tagName: "td"): HTMLTableDataCellElement;

will tell TypeScript that calling this line :

var a = document.createElement("td");

will produce variable a of type HTMLTableDataCellElement.

Then logically this snippet should work fine (but its not):

if (a instanceof HTMLTableDataCellElement) {
   //a is here of type HTMLTableDataCellElement with all IntelliSense props as expected in VS
} else {

If you just want to have a type at compile time there is no need for worries (just IntelliSense in VS or any other editor). You are fine.

At runtime, this will fail because Chrome and FireFox don’t know what HTMLTableDataCellElement is. But they know HTMLTableCellElement : https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement.

Also it turns out that in lib.d.ts interface HTMLTableDataCellElement inherits HTMLTableCellElement so we are safe (I think at least, because HTMLTableDataCellElement  isnt extending HTMLTableCellElement  with anything) to say that we can define variables of type HTMLTableCellElement like this :

var res: HTMLTableCellElement = document.createElement("td")

and at runtime check for these like this :

object instanceof HTMLTableCellElement

and everything should work as expected.

From my point of view, I would personally drop HTMLTableDataCellElement definition. I find it misleading.

Please note I did this code with TypeScript 1.5 beta downloaded from here : http://blogs.msdn.com/b/typescript/archive/2015/04/30/announcing-typescript-1-5-beta.aspx.

How to get type of object in TypeScript, when using union types and type guards for multiple types of function parameter or variable

tl;dr

When checking for primitive types in TypeScript , typeof variable === “string” or typeof variable === “number” should do the job.

When checking for HTMLElement or HTMLDivElement type of objects, variable instanceof HTMLElement or variable instanceof HTMLDivElement type of check should be the right one.

Please note that this is somewhat simplified point of view. I was only using simple objects and elements from one page. If you will run into some specialties, please read this article : http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ and write as much unit tests as possible for you scenario. There might be some scenario where using typeof and instanceof are simple not enough.

The whole story :

My beloved TypeScript 1.4 we got a while back came with a new lovely possibility of having parameters passed as object that might be of several different types. For example you can accept either string or array of strings, where if passed a plain string, you can split it and continue with array of strings or use directly passed array.

We can argue if this is a good and clean solution from architectural point of view, but if for whatever reason this will be a requirement how the function should work, than we can leverage two sweet features of TypeScript :

Both might be used also separately or with some plain var in your code (you can just define var that will be of types string | HTMLElement | number) but if used together, Type Guards are building on top of Union Types feature and giving you some sweet stuff.

So what you get is, that TypeScript now understands what are you doing, when you check for one of types that variable might be of and you can get IntelliSense for that type (I am little fast forwarding here to the function I want to show you but this is what I mean by that) :

param check intellisense

And here I am getting to the main point of this particle and that is : how can we check for HTML elements of any other object from the DOM world?

As you all know, getting the basic types in JavaScript if quite difficult if you run into edge cases or the type you check for might be also array or stuff like that. You can read great article like this one : http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript. There are many caveats. 🙁

typeof will do, for the most part :

But most of the time, for basic types we are OK with using typeof operator and comparing against “string” or “number” but what about HTMLElement or HTMLDivElement object in TypeScript? Do the exist in the vast and wild JavaScript world? Yes the do exist, but dependent on the browser age with different results. Another misleading thing is that unfortunately the typeof operator will not work we want for HTMLElement and similar types of objects, but neither will the approach create an error, because every time we would get string “object” which is OK from inheritance point of view but its not what we need.

instanceof to the rescue :

What will work here is instanceof operator.  Nice article also here : http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for. Again, there are some caveats here (like this http://stackoverflow.com/questions/472418/why-is-4-not-an-instance-of-number) when used with primitive types like string, so I advice you to stick with instanceof for instances of objects or for checking of types from the DOM side of the world.

The snippet :

And here it is ladies and gentleman, the glamorous sample snippet I wanted to share with you (for testing purposes):

export function parCheckDemo(param: string | number | HTMLElement | HTMLImageElement | HTMLDivElement): void {
    if (param instanceof HTMLDivElement) {
        console.log('HTMLDivElement');
    } else if (param instanceof HTMLImageElement) {
        console.log('HTMLImageElement');
    } else if (param instanceof HTMLElement) {
        console.log('HTMLElement');
    } else if (typeof param === "string") {
        console.log('string');
    } else if (typeof param === "number") {
        console.log('number');
    } else {
        console.log("You're not supposed to be here! - Levelord");
    }
}

Hope this helps dear reader, enjoy. If you have any suggestions to the code, please feel free to share in the comments.

PS: yes, in real life I (and you too) should probably first check if anyone passed something as param argument , this snippet is jut for demo purposes.

How to force types in Array with TypeScript’s union types

From TypeScript 1.4 we can do nice stuff with types now, with help of feature called Union Types : https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#union-types which will let you do also this sweet stuff :

ts union types

You can see this in action on this link :

http://www.typescriptlang.org/Playground

Sample snippet here :

module ArrPlayground {
    export function fn() {
        var arr: Array<boolean|string> = [];
        arr[0] = "aaa";
        arr[1] = false;
        arr[2] = 987;

        return arr;
    }
}

Basically you can now limit types that could be used in Array (all only at compile time, same rules apply as for other type checking features of TypeScript).

Enjoy.

Adding .JS file generated by TypeScript in Visual Studio 2013 to markup

Note to self :

If you want to add .js file generated by TypeScript from .ts file under Visual Studio 2013, you don’t need to click Show All Files, than search for file you wanted to add and then disable Show All Files (because by default, .js and map files are not part of project). You can just drag and drop .ts file to .html or .aspx markup and Visual Studio 2013 is intelligent enough to include .js file. Fast, simple, obvious. Not for all however 🙂 .