What is Typescript?
Typescript [typescriptlang.org] is a tool and programming language to generate Javascript code. Javascript is a terrible, terrible language—that we're forced to use because it's never going away—so there have been multiple languages created just so we don't need to write raw Javascript. Typescript is Javascript with types, with static type checking, which reduces a lot of potential errors in complex codebases before the code is even run.
Example of Typescript Code
Typescript is essentially the same thing as Javascript but with type annotations and type declarations that Javascript doesn't support. It's possible to do much of what Typescript does with JS Doc, which reads type annotations from code comments, but Typescript provides a terse, powerful way to express even complex types.
function foo(bar: number, baz?: string): number | string {
return baz ? baz : bar;
}
When you compile the code above with npx tsc
(Typescript's compiler running inside Node), it generates the following Javascript code:
function foo(bar, baz) {
return baz ? baz : bar;
}
As you can see, it's literally the same thing, except without types.
Observation: it seems that many beginners to web development are introduced directly to Typescript and React instead of to raw Javascript first. While that's a nicer world to live in, it creates a bunch of confusion. You see many beginner questions asking "how to do X" in Typescript, when the actual question is about algorithms or APIs that are from Javascript.
For example, "how to iterate over an array" is Javascript functionality (for(let it of arr)
), and has nothing to do with Typescript.
Meanwhile, "how to declare that an argument can be null but not undefined" is Typescript (baz: string | null
). This could be asked in a Javascript forum, but all you would be told is that "Javascript can't do that, use Typescript for that."
A cool example is "how to call a function passing an array as arguments." In Javascript, this is done with foo.apply(arguments)
. In Typescript, it's the same thing, but if you have a variable that is a tuple and you're targeting a version of Javascript that doesn't support "rest" parameters, doing foo.apply(...tuple)
in Typescript, where tuple: [number, string | undefined]
, transpiles to foo.apply(tuple)
.
Typescript issues are all related to Typescript's static type checking.
On top of that, React doesn't use normal Javascript. Although it can be programmed with normal Javascript, generally you will use React with JSX, which allows you to type HTML tags into the Javascript code. This introduces a build step to transpile JSX into the Javascript equivalent so web browsers can understand the code you typed. If you use Typescript AND React, you get something that is neither Typescript nor JSX, but TSX.
Leave a Reply