Burt_Harris Burt_Harris - 1 year ago 100
TypeScript Question

TypeScript migration: Simplest fix for JavaScript style const definitions generating errors?

I'm experimenting with migrating a moderately large project from JavaScript to TypeScript by renaming

file to
. The project is large, I'm starting with small examples. The JavaScript code is already class like, and I've chosen a simple class
class with no dependencies to start with. A simplified version appears below, the bottom line of which generates an error using tsc 1.8 saying "Property 'INVALID_TYPE' does not exist on type () => any."

function Token() {
this.source = null;
this.type = null; // token type of the token
this.line = null; // line=1..n of the 1st character
this.column = null; // beginning of the line at which it occurs, 0..n-1
return this;


I understand how, by converting
function Token
into a
class Token
, I can make
a static member of class
, but doing this across nearly 10k lines of code becomes rather complex. I'm looking for a more incremental approach. One simpler approach to eliminating the errors is to change the last line to:

(<any>Token).INVALID_TYPE = 0;

Is there better quick-fix to temporarily eliminate this kind of TypeScript error message?

Answer Source

A quick fix would be to rewrite the function declaration as a function expression (make sure there are no issues from the loss of hoisting!) and cast it to the any type, you can then add whatever props you want.

const Token = <any> function() {
  // ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download