TypeScript
TypeScript is basically a superset of JavaScript.
This means that
- JavaScript code works in TypeScript
- if you know JavaScript, TypeScript is not that difficult to learn
However, TypeScript works more like a compiled language. In other words, you have to solve errors before your program is able to run/execute.
In fact, the way a program written in TypeScript works is through compilation to vanilla JavaScript using tsc. (TypeScript Compiler)
Classes - OOP
Declaration
Instantiation
Value assignment
Constructor
readonly
Readonly fields are only assignable on declaration or inside the constructor.
Inheritage
Just as in JavaScript, if you have a base class, you’ll need to call super(); in your constructor body BEFORE using any this. members.
Getters / Setters
Variables
Notice how
and
are equal in TypeScript.
Unknown
In TypeScript, the unknown type works similarly to any but not quite the same.
In the above example, assigning the value of varUnknown: unknown to a variable without explicit assertion throws an error. This happens cause the compiler has no idea what the variable’s type is.
For the same reason, we cannot call any methods of the unknown variable.
However, it is possible, again, with explicit assertion.
Why use
unknownat all?Well, it is very useful in situations that you don’t know what the type of an object is going to be and you have to check before you use it. It is stricter than
anyand less risky.
Example:
The above example accepts an unknown parameter and returns true if it contains a property named myProp. Else, it returns false.
Interfaces
Arrays
but
Tuples
Generics
Conditional Types
Conditional types help describe the relation between the types of inputs and outputs. Basically, you can change the type of an object based on the type of another.
Also, there are some interesting things that conditional types enable us to do. For example, you may want a variable to only take values that exist as keys in an object.
Memoization
Memoization is an optimization technique, to reduce the complexity of the application, runtime of the application, and proper utilization of resources (Time and Memory).
What this means? It means that if you have a function that takes a long time to execute, you can store the result of the function in a variable and return that variable instead of executing the function again.
The above code is a simple fibonacci implementation. The result is calculated each time the function in called.
The above code is the same as the previous one, but with memoization. As we call it 5 times, the result is calculated only once in the first call and then returned from the cache for the rest.
Snippets
Objects as Maps
Now you can use arbitrary strings to look up a value.