Type System Fundamentals
Installation
# enables tsc yarn global add typescript
Typescript is a superset of JS
TS is just a JS generator
Typescript code is compiled to plain JS
- Notion of type goes away once TS is compiled to JS
Compile Time
Type Checking
Typescript is a static type checker for Javascript
- These checks take place during
compile time
There is NO runtime
type guarantee in Typescript
TS 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 no runtime guarantee behavior is in data fetching.
- When you fetch the data from an API, file, or user input, there is no guarantee during compile time whether the shape of the data returned is identical to the shape you've declared to the compiler
- This will result in a runtime error even though TS is ok with the shape of the data
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
- Inferred types are the expectations 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 systems are used to determine if types are equivalent and whether a type is a subtype of another
Structural Subtyping
type A
is a subtype
of another type B
, if A
contains at least the same attributes 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)
- 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 Typescript
Fundamental 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
- this means that a
type alias
is completely interchangeable with the type it is equal to- In above example, we have a type alias that can be replaced with an object literal