TS is just a JS generator
Typescript code is compiled to plain JS
Compile Time
Type CheckingTypescript is a static type checker for Javascript
compile time
runtime
guarantee in TypescriptTS does not provide runtime type information or runtime type checking
This is why libraries such as zod
, yup
, joi
, and etc. because they provide the runtime data validation.
Best illustration of this issue is data fetch.
Type Inference
IDE such as VSCode comes with a lot of critical tooling for using TS. It is good idea to trust and use those tools.
Rely on the inferred types from the IDE
Structural Type System
Structural type system is where type compatibility and equivalence are determined by the type's actual structure or definition and not by other characteristics like name or place of declaration
Structural Subtyping
type A
is a subtype
of another type B
, if A
contains at least the same "stuff" as B
(the same public methods, etc.) and has invariants
which are at least as strong (in other words, if the invariant of A is satisfied, the invariant of B is also satisfied)
invariant
In OOP, invariant
is a set of assertions that must always hold true during the life of an object for the program to be valid
Object
is important in TypescriptFundamental way we group and pass around data in JS is through an object.
Object matters in Typescript because the objects' shapes are what is being used by Typescript for type comparison (Structural Type System
)
There are multiple ways of representing the object in Typescript:
// object literal function greet(person: { name: string; age: number }) { return "Hello " + person.name; }; // type alias type Person = { name: string; age: number; }; function greet(person: Person) { return "Hello " + person.name; }; // interface interface Person { name: string; age: number; }; function greet(person: Person) { return "Hello " + person.name; };
type alias
type alias
doesn't create a different type, it's just another name for one that already exists in the system
type alias
is completely interchangeable with the type it is equal to