DEV Community

Cover image for Getting Started With TypeScript
Chinmay Mhatre
Chinmay Mhatre

Posted on

Getting Started With TypeScript

I'll proceed with the blog assuming you have previously worked with JavaScript. Knowing JavaScript would have you catch on to TypeScript concepts pretty easily.

Typescript has gained a lot of popularity over the years since it was made.
graph
credits: The State of the Octoverse

Looking at issues you might run into in JavaScript

Let's start with a simple problem. Say we have a object that has these properties.



    const person = {
        name: 'John',
        age: 30,
        hobbies: ['Sports', 'Cooking']
    }


Enter fullscreen mode Exit fullscreen mode

After writing plenty of code we wanted to access a property of this object. We forgot the object doesn't have a property called "lastName" but we tried to access it anyways.



    const lastName = person.lastName;


Enter fullscreen mode Exit fullscreen mode

JavaScript won't throw an error but it will return undefined. Now imagine, the variable getting passed through multiple layers of functions .
Locating the point of error would drain the life of our finitely mortal life.

We can solve this problem by using TypeScript.

being able to access a variable not present.
multiple null.
Enter fullscreen mode Exit fullscreen mode

fixes JavaScript problems with types.

Types

Types are basically the kind of data that a variable can hold. Some primitive types of types are: Integers, Strings etc.

If anyone comes from a C++, C or a Java background, they would know about types.

In JavaScript when we declare a variable



    let name = 'John';
    const age = 30;


Enter fullscreen mode Exit fullscreen mode

Here in both age and name any kind of data can be stored. While this may seem convenient to a developer in the beginning is a nightmare while debugging if you input a wrong type of data.

Static type checking

Typescript is what we call a static type checker. It
checks for errors relate to types before we run our code.
TypeScript doesn't really run our code. It performs this type checking before we run our code using JavaScript.

After compiling Typescript is compiled to JavaScript which can be executed as usual.

If we take the above example in TypeScript we can see the compiler warn us before even running our code.

Typescript

Running TypeScript

TypeScript cannot be run directly through the browser or node. TypeScript is compiled to JavaScript. To do so, we install typescript globally using npm.



npm i -g typescript


Enter fullscreen mode Exit fullscreen mode

Once we have installed TypeScript globally, we get access to the tsc command.

We'll look at running TypeScript and it's many features in the next blog.

Top comments (19)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

What that means is all the JavaScript you know is completely valid in TypeScript

TypeScript is not a superset of JavaScript. This perfectly valid JS throws an error in TS:

var foo = {};
foo.bar = 42;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tylim88 profile image
Acid Coder • Edited

it error because it does not pass the type check (that is the purpose of typescript: type check)

doesn't mean typescript is not super set of javascript

a valid JS code that does not pass typescript type check only throw error on compilation but not run time

var foo = {};
// @ts-expect-error
foo.bar = 42;
console.log(foo)
Enter fullscreen mode Exit fullscreen mode

simply expect the error and you can run the code
playground

Collapse
 
rkallan profile image
RRKallan

Instead using

// @ts-expect-error
Enter fullscreen mode Exit fullscreen mode

Add a dynamic type and defined possible types for value

type TypeFoo = {
    [key: number | string]: string | number | string[] | number[] | undefined 
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
tylim88 profile image
Acid Coder • Edited

the reason i use // @ts-expect-error is because I want to show that untyped code is a valid code in TS

also [key: number | string] in unnecessary because it is equivalent to [key: strting]

dev.to/tylim88/typescript-caveat-1...

Thread Thread
 
rkallan profile image
RRKallan

also [key: number | string] in unnecessary because it is equivalent to [key: strting]

True Sorry my mistake. Object keys is always a string.

the reason i use // @ts-expect-error is because I want to show that untyped code is a valid code in TS

ts-expect-error will report if there is no error.
Unused '@ts-expect-error' directive
Which can be solved with
// @ts-ignore

It’s a choice of course.

Thread Thread
 
tylim88 profile image
Acid Coder • Edited

ts-expect-error will report if there is no error.
Unused '@ts-expect-error' directive
Which can be solved with
// @ts-ignore
It’s a choice of course

which is why you should only use it on line that has error

normally // @ts-ignore is not desirable because it is not granular, it will just ignore everything and will ignore thing that you don't want to ignore (but is ok in this case)

and because of granularity // @ts-expect-error is very useful in type testing

True Sorry my mistake. Object keys is always a string.

object key can be numeric, it will be converted to string on runtime

type wise key type of both {[x:string]:unknown} and {[x:string | number ]:unknown} are string | number

which is why I said it is unnecessary, not incorrect

Thread Thread
 
rkallan profile image
RRKallan

TS expect / ignore

The ideas which when to use, have you points to add? Or other advice?

Thread Thread
 
tylim88 profile image
Acid Coder

a good analogy is something like const and let vs var

in what case you need var? almost none

so I never use ts ignore, I only use ts expect error

if you find yourself in need of ts ignore, you probably need refactoring or you have compatibility issue

Collapse
 
jonrandy profile image
Jon Randy 🎖️

If some valid JS throws an error in TS, then - by definition - TS cannot be a strict superset of JS

Thread Thread
 
tylim88 profile image
Acid Coder

I am not sure where did you get that definition

here is the definition from wikipedia

TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language.

en.wikipedia.org/wiki/TypeScript

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

I'm going by the definition of 'superset' - a set that contains another set. So if the set of valid JS contains things that are not in the set of valid TS, TS CANNOT be a superset of JS.

The key part of the wikipedia definition is 'syntactical' - the JS example given is syntactically valid in TS, but will cause an error. This is an important distinction. Far too many people believe all JS code will run just fine in TS because 'TS is a superset of JS' - but this just isn't the case.

I've also seen examples of valid JS that will do something quite different in TS.

Thread Thread
 
tylim88 profile image
Acid Coder • Edited

So if the set of valid JS contains things that are not in the set of valid TS

I want to clarify that JS code is indeed valid in TS, TS understand the JS which is why it is able to point out the type mistake (which is the purpose of TS)

and you can by pass the error(ignore it or type cast it), the compiler will still emit the same code where you type it correctly or not

it is like TS saying: "Heh man I know what you are trying to do, and I and not quite happy with it, but if you insist to go on, I will just let it pass"

If JS is not a valid TS code, TS wont even able to understand it at all and respond it with error like invalid syntax

I've also seen examples of valid JS that will do something quite different in TS.

not saying typescript compilation is completely fine, but this is something that common outside of typescript, for example babel plugins that compile same JS code differently, there is just too many way to compile JS

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

and you can by pass the error(ignore it or type cast it), the compiler will still emit the same code where you type it correctly or not

You mean it will leave the JS unchanged? This is not true either (I believe even the TS docs mention this) - some valid JS will be altered by the TS compiler.

Going back to the superset thing - if you take out 'syntactically', then it is possible to argue that TS is actually a subset of JS (or contains a subset of It). Why? Because it's possible to do things in plain JS that it isn't possible to do in TS (without modifying the JS to please the compiler, or turning off TS error checks - but then the code is compiled back to JS anyway)

Thread Thread
 
tylim88 profile image
Acid Coder • Edited

I mean the properly typed and improperly typed will still produce the same code

the type notation will not affect the final JS code emitted

for example If TS decide to compile a to b, with or without the type annotation, the result will still be b

whether a should be b, whether it makes sense or not, is another story

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

TS will mangle this valid JS code - making it do something different:

function f(a) { return a; };

console.log(f<Function>(f)); 
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
tylim88 profile image
Acid Coder • Edited

Because it's possible to do things in plain JS that it isn't possible to do in TS

this should be counted as deficiency, bug, or todo

TS will mangle this valid JS code - making it do something different:

ya like I said, whether 'a' should compile to 'b' is another story, even babel itself has many way to compile the same JS code, and by this logic should we say JS itself is invalid JS?

It really depend on the understanding of the author, they could be right, they could be wrong

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Yep, the problem is (as I said) - the widespread misunderstanding of what 'TS is a superset of JS' actually means. I've lost count of the number of times I've heard people say that 'all your existing code written in JS will run with no problems in TS, you can just add the types gradually' - and then watching the ensuing chaos.

I've written libraries for JS that some really good TS developers I know have tried to make compatible with TS... they gave up!

TS can certainly be the right tool in some situations, but other situations it actually blunts the power of JS.

Thread Thread
 
tylim88 profile image
Acid Coder

The misunderstanding is people think by copy and paste think will work

No, by superset it means the compiler understand JS syntax

it has nothing to do with the effort of the developer, it is not about the developer!

Collapse
 
rkallan profile image
RRKallan

I wouldn’t recommended to install TS global, I would recommend to install it as dependacy. So you will be sure all teammembers will use the same TS version

npm install typescript --save-dev
Enter fullscreen mode Exit fullscreen mode

You can use is as follow with npx

npx tsc
Enter fullscreen mode Exit fullscreen mode