Last active
August 29, 2015 14:06
-
-
Save jotak/eac2aca66591b3b7cbb2 to your computer and use it in GitHub Desktop.
Does Typescript make javascript safe? Not so sure about that...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
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 []; | |
} |
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"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.