Skip to content

Instantly share code, notes, and snippets.

@jotak
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jotak/eac2aca66591b3b7cbb2 to your computer and use it in GitHub Desktop.
Save jotak/eac2aca66591b3b7cbb2 to your computer and use it in GitHub Desktop.
Does Typescript make javascript safe? Not so sure about that...
// ...
app.get(libRoot + '/get/:start/:count', function(req, res) {
getSongsPage([/*some data*/], req.params.start, req.params.count);
// ...
});
// ...
function getSongsPage(allSongs: SongInfo[], start: number, count: number): SongInfo[] {
console.log("start=" + start);
console.log("count=" + count);
console.log("start + count=" + (start + count));
console.log("typeof start=" + typeof start);
console.log("typeof count=" + typeof count);
console.log("typeof (start + count)=" + typeof (start + count));
var end: number = Math.min(allSongs.length, start + count);
if (end > start) {
return allSongs.slice(start, end);
}
return [];
}
@jotak
Copy link
Author

jotak commented Sep 27, 2014

Typescript comes on top of javascript and adds cool typing features, allowing to create safer code. But maybe not as safe as you would expect...

The above code show the following results:

start=2000
count=1000
start + count=20001000
typeof start=string
typeof count=string
typeof (start + count)=string

I would naively expect the "getSongsPage" method can only be called with "number" parameters, and that the compiler would produce errors when used with strings. It doesn't, because it doesn't do miracles. At some point, when interfaced with existing native JS libraries (here with "express" nodejs module), the compiler lacks of typing information, and says everything's all right even when it's not :(

Typescript can give a dangerous feeling of security for non-experts.

@jotak
Copy link
Author

jotak commented Sep 27, 2014

See also some nice articles: "Why TypeScript Isn't the Answer" http://www.walkercoderanger.com/blog/2014/02/typescript-isnt-the-answer/ from serie of articles "The JavaScript Minefield"

@bartavelle
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment