TypeScript
TS is a syntactic super-set of JS which adds static typing
TLDR: JS has a lot of BS, TS adds type safety.
TypeScript uses compile time type checking. Which means it checks if the specified types match before running the code, not while running the code.
A common way to use TS is to use the official TS Compiler, which transpiled TS --> JS.
npm i typescript --save-devYou can run the compiler with:
npx tscYou can configure the TS compiler using a tsconfig.json file. It can be generated with:
npx tsc --initThe above is just one option to get started with TS; you can also use create-react-app then check off TS, etc...
npx create-react-app <app_name> --template typescriptnpx create vite@latest <app_name> --template react-tsnpm create-next-app@latest --ts
Simple (Primitives) Types
There are three main primitives in JavaScript and TypeScript.
boolean- true or false valuesnumber- whole numbers and floating point valuesstring- text values
Type Assignment
When creating a variable, there are 2 main ways to assign a type:
Explicit- writing out the type:easier to read and more intentional
Implicit- TS will infer the type based on the assigned value:shorter, faster, and more often used when developing and testing
Type Assignment Error
TS will throw an error if data types don't match
Unable to Infer
TS may not always properly infer the variable type.
In such cases, it will set the type to
any, which disables type checking
Special Types
TS has special types that may not refer to any specific type of data.
> Type: any
type that disables type checking and allows all types to be used.
> Type: unknown
similar, but safer alternative to any.
TS will prevent unknown types from being used
best used when you don't know the type of data being typed.
To add a type later, you'll need to cast it.
Casting is when we use the "as" keyword to say property or variable is of the casted type
> Type: never
never effectively throws an error whenever it is defined.
> Type: undefined & null
undefinedandnullare types that refer to the JS primitivesundefinedandnull, respectively.
These types don't have much use unless strictNullChecks is enabled in the tsconfig.json file.
Arrays
For Explicit assignment, add a [ ] after the value type (number[ ], ...)
Readonly
The readonly keyword can prevent arrays from being changed.
Type Inference
TS can infer the array type based on its values
Tuples
array w/ a pre-defined length and types for each index and allow for arrays with different types, all of which are known.
Defining Tuple
To define a tuple, specify the type of each element in the array:
Readonly Tuples
It is suggested to make tuples readonly since there's no type safety in the tuple outside the first n indexes with strongly defined types:
Named Tuples
Named tuples allow us to provide context for values at each index:
Destructuring Tuples
Since tuples = arrays, we can also destructor them:
Object Types
TS has specific syntax for Objects (python dictionaries). It basically adds a schema for each Object, allowing for inferences and type safety.
Optional Properties
properties followed by a ? don't have to be defined during Object definition.
Index Signatures
When you don’t know all the names of a type’s properties ahead of time, but you do know the shape of the values, you can use an index signature to describe the types of possible values:
Enums
enum is a special class that represents a group of 'const' variables. They come in 2 flavours: numeric and string.
1. Numeric Enums
Default Numeric Enums: where enums will initialize the first value to 0 and add 1 to each additional value:
Initialized Numeric Enums: where you set the value of the first numeric enum, and have it auto increment after that:
Fully Initialized Numeric Enums: where you set unique numeric values for each enum value (no auto increment)
2. String Enums
TS allows types to be defined separately from the variables that use them. You can use Aliases & Interfaces to be easily shared b/n different variables/objects.
Type Aliases
doesn’t actually create a new type - it creates a new name to refer to that type.
Interfaces
similar to type aliases, except they only apply to OBJECTS
Interfaces can EXTEND other interfaces (union) using the extends keyword:
Union Types
used when a value can be > 1 type
using the | like: | , we are saying that _ is type1 or type2
Functions
TS has specific syntax for adding types to fx parameters & return values:
Export & Import Functions
Use named exports (unlimited exports in a file):
Use default exports (1 per file):
If you have a file that does 1 default export & many named exports:
Function Overloading
Overloading - same name, different parameters and return types
Method 1:
Method 2: Define so-called *overload signatures* & an *implementation signature*
overload signatures don't have a body; they only define params & their types
the implementation signature has a body and defines params & their types
Casting
allows you to convert a variable from 1 type to another.
Casting w/ as
Casting w/ *<>*
Basic Generics
Suppose you have an array; 'A' list of items. You don't know what the items are nor do you care. This means that you have an array of generic A elements. What A is is IRRELEVANT.
Many DS&A do not depend on the actual type of the object. However, you still want to enforce a constraint between various variables. Ie. a list reversal algorithm:
Type Aliases (and also for Interface)
Generics in type aliases allow creating types that are more reusable.
Default Value
Generics can be assigned default values which apply if no other value is specified or inferred.
Extends
Constraints can be added to generics to limit what's allowed
Utility Types
TS comes with a large number of types that can help with some common type manipulation, usually referred to as utility types.
Partial
all the properties in an object are now optional.
Required
all the properties in an object are now required.
Record
shortcut to defining an object type with a specific key type and value type.
Omit
removes keys from an object
Pick
removes all but the specified keys from an object
Last updated