TYPOS IN TYPESCRIPT

One problem I encountered was when I made a typo while converting a prototypical class and I was chopping the  “class.prototype’ out of the function declarations and replacing it with the private or public keyword.  For example a class like so

var MyNamespace = MyNamespace || {};

MyNamespace.Widget2 = function(inp,a,b)
{
	this._a = a;
	this._b = b;
	this._inp = inp;
}

MyNamespace.Widget2.prototype.create = function()
{
	this.click();
}

MyNamespace.Widget2.prototype.method1 = function(x)
{
	alert('hello');
}

MyNamespace.Widget2.prototype.click = function(e)
{
	this.method1();
}

Was converted to

module MyNamespace
{
	export class Widget2
	{
		private _a : number;
		private _b : number;
		private _inp : number;

		constructor (inp,a,b)
		{
			this._a = a;
			this._b = b;
			this._inp = inp;
		}

		public create()
		{
			this.click();
		}


		public method1(x)
		{
			alert("hello");
		}

		public click = function()
		{
			this.method1();
		}

	}
}

Note what I consider the typo – the click function was not completely converted, I forgot to strip the ‘= function’  and now it is an assignment to a variable, but it is perfectly valid TypeScript.  and it will run correctly. The problem is ‘this’ in the function is not typed as Widget2 but as ‘any’. Now the code will run fine BUT if you make any modifications to the use of ‘this’ in the function you will not get the protections afforded by TypeScript – for example the following class will compile perfectly fine due to ‘this’ being typed as ‘any’, and fail at runtime.

module MyNamespace
{
	export class Widget2
	{
		private _a : number;
		private _b : number;
		private _inp : number;

		constructor (inp,a,b)
		{
			this._a = a;
			this._b = b;
			this._inp = inp;
		}

		public create()
		{
			this.click();
		}


		public method1(x)
		{
			alert("hello");
		}

		public click = function()
		{
                        // method name incorrect 
			this.mthod1();			
		}

	}
}

The recommendation I have for this situation if you are converting a large codebase is to do a regex search in Visual Studio on

(public|private)?s+($|w|_)+s+=s+function

And see if you have made the mistake yourself. If you use unicode characters in your identifiers you will have to update the regex

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

OR

LOGIN OR REGISTER

Registered users with one approved comment can comment without moderation