Preparation
Please refer to this documentation for installation. Personally, I use volta to install TypeScript. I use bun to install typescript compiler bun add -g typescript. Check your installation using:
|
|
Your First TypeScript Program
Create a project folder, e.g., belajar, then create a file app.ts
|
|
Then run:
|
|
The --outDir flag will create a folder called dist where the compiled JS file is stored, and the --watch flag will watch for any changes in app.ts.
Init Config file
run tsc --init, then it will create a config file tsconfig.json. set the outDir value as follow
|
|
open pallet command cmd/ctr + shift + p and select Tasks: Configure Task -> tsc: build - tsconfig.json
create a launch.json file via ‘RUN AND DEBUG’ vsCode menu then choose Node option. The new file tasks.json will be created. Set the configuration as follow
|
|
Create launch.json via debug in VsCode menu
create launch.json
and put the following configuration
|
|
then you can just press f5 button to compile and run the program. Or simply run with command bun app.ts
Optionally, we can add settings.json to the .vscode folder for formating purpose with this following content
|
|
Data Type
Basic Primitive
There are three basic types: string, number, and boolean. can be writen with or without anotation like below
|
|
Interface vs Alias
The differences between Interface and Alias already mentioned in the documentation here.
A good rule:
- interface → object shapes and contracts
- type → more complex type compositions
let’s breakdown
- Use
interfaceswhen defining objects, class contracts, or APIs. - Use
typefor unions, primitives, and advanced types
|
|
- Use
typefor complex type composition Type aliases are great for mapped types, intersections, generics, etc. example:
|
|
intersection example:
|
|
Interfacesupports declaration merging This “declaration merging” feature is mostly useful if you are working with interfaces that are coming from another file or, more commonly, from some library or anything like that, so where you maybe want to extend something you don’t directly control. If you want to add a property to some interface you don’t directly control, you could do that with “declaration merging” like this.
|
|
Interfaceswork better with classes. Interfaces are ideal when classes implement them. This is a very OOP-style contract.
|
|
- Performance considerations. The TypeScript team has mentioned that interfaces are slightly better optimized for large object hierarchies. so many teams prefer:
|
|
instead of
|
|
Example
Example in a Qwik or React project.
Interface for component props:
|
|
Type for variants:
|
|
Enum
In TypeScript, there are three common ways to create enum-like data types. The built-in enum, and two modern alternatives using union types and const objects.
Many modern projects actually avoid enum and prefer union types, but it’s important to know all approaches.
ref https://www.typescriptlang.org/docs/handbook/enums.html
Using the built-in enum
example
|
|
Usage:
|
|
String enums example. These are more common because they are readable.
|
|
Usage
|
|
Enum with union type
Many teams avoid enums and use union types.
|
|
Usage
|
|
Enum pattern with as const
Another powerful pattern
|
|
create type from object
|
|
usage
|
|
Interfaces
- contract that define types
- compiler enforces the contract via type checking
- collection of property and method definition
- duck typing
|
|
Demo
create app.ts file with content
|
|
try to remove one of property of a book element, for instance the book id 1 to be
|
|
We will get the error because every property must be declared in object of interface.
Interface for Function types
We can use interfaces to give those function types names. The CreateBookID function takes string and number parameters and returns a string.
|
|
then we can define the variable IdGenerator with anotation type from the function parameter to accept the CreateBookID
|
|
That all work fine, but if I wanted to use it in multiple places, it would be better to have the type defined in a single place. Then the code will be like below
|
|
Extending Interface
we can extend the interface from another interface like the code below
|
|
Classes
references: https://www.typescriptlang.org/docs/handbook/2/classes.html
- template or blueprint for creating object
- provides state storage and behavior
- encapsulates reusable functionality
What we will learn:
- define types
- properties and method
- constructors
- access modifiers
- inheritance
- abstract classes
Modules
references: https://www.typescriptlang.org/docs/handbook/2/modules.html
Advanced Type
Function Overload
suppose we have
|
|
then if we want to get output length from the string input
|
|
we will get an error
|
|
we can add as string to solve the problem
|
|
also we can use Function Overhead
|
|
references: https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads
Asynchronous Code
Promise
The promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
- native support in ES2015
- requires typescript
--targetcompiler option set to ES2015 or greater
- requires typescript
- small API
- then
- catch
- similar to
Tasksin C# - may be chained together
- created by passing function to the promise constructor
async/await
- allows code to be written more linearly
- very similar to async/await in C#
- work with promise