Getting started with TypeScript.
Sep 2024
TypeScript is a superset of JavaScript, providing type safety and static type checking. It is a statically-typed language.
In statically typed languages, the data type of a variable is known at compile time, while in dynamically typed languages, the data type is assigned during runtime by the interpreter, depending on its value.
TypeScript is primarily a development tool, where the project still runs JavaScript.
.tsprogram, follow these steps:
The first step involves transpiling, where the TypeScript compiler transpiles the TypeScript code to JavaScript. Transpiling is the process of converting the source code from one programming language to another. It is often used in web development, especially with languages like TypeScript and JSX, which are not directly supported by web browsers.
In TypeScript, primitive types such as string, number, and boolean are used to represent basic data types.
Note: JavaScript does not have a special runtime value for TypeScript types, so there's no equivalent to "int" or "float" - everything is simply number.
However, it's not always necessary to explicitly specify types. In some cases, TypeScript can infer types based on the assigned values. Overusing types can make the code verbose and less readable.
any. However, using
anyis discouraged as it disables type checking. It's recommended to specify types explicitly or use the compiler flag
noImplicitAnyto flag implicit
anytypes as errors.
Type annotations for functions are strong and recommended.
Arrow functions provide a concise syntax for writing functions.
nevertype represents values that are never observed. In a return type, this means that the function throws an exception or terminates execution of the program.
When a function is called with an optional parameter, it throws an error. However, if an object with an optional property is created and assigned to a variable, calling the function with that variable does not result in an error.
Type Aliase is a name for any type. This is convenient, but it's common to want to use the same type more than once and refer to it by a single name.
readonlyis used to make a property unchangeable, the value cannot be changed after it is set.
?marks the property as optional.
[1,2,3], you can use the syntax
number[], this works for any type (e.g. string[]).
|) to separate each type.
Note: Direct manipulation on individual types is not allowed because TS treats the union type as a new data type.
Tuples are typed arrays of pre-defined length and types for each index. The order of data type in each index should be maintained.
Array methods are allowed on tuples that violate type safety, so a good practice would be to make a tuple "readonly".
A special class that represents a group of constants, can be string or numeric.
First value is initialised to 0 by default then 1 is added to each additional value.
We can also set the value and have it auto increment from that.
Or we can initialise all the values.
Used to define shape/structure of objects. Interfaces are similar to type aliases, except they only apply to object types.
Interfaces can extend each other's definition. Extending simply means you are creating a new interface with same properties as that of the original interface, plus something new.
Type: Types can be used to define simple types, union types, intersection types, and more.
Interface: Interfaces are typically used for defining object shapes.
Type: Types can be used to create union or intersection types, but they cannot be extended or implemented.
Interface: Interfaces can extend other interfaces and can be implemented by classes.
Type: Types don't support declaration merging.
Interface: Interfaces support declaration merging, which means you can declare an interface multiple times, and their members will be merged.
tsconfig.jsonfile
tsconfig.jsonis a configuration file used by the TypeScript compiler (tsc) to specify compiler options and project settings for a TypeScript project. This file allows developers to define various settings such as compilation target, module system, output directory, and more.
distand
srcfolders.
index.htmlfile and make it point to
index.jsin the
distfolder by adding a script tag.
index.tsin the
srcfolder.
tsconfig.json
distdirectory.
.tsfile.
.tsfile.
This command runs TypeScript files in "watch mode", allowing the compiler to detect changes and recompile automatically.
TypeScript offers full support for the class keyword introduced in ES2015.
publicwriteable property on a class.
getand a setter method starts with the keyword
set.
Note: A set accessor cannot have a return type annotation.
extendskeyword.
privatekeyword: private access modifier makes the field only accesssible inside a class.
protectedkeyword: protected members are only visible to subclasses of the class they’re declared in.
superkeyword: It allows us to invoke constructor of parent class, call parent class methods within a subclass. The
superkeyword is useful for overriding and extending the behavior of methods defined in a parent class, especially when those methods are not declared as
private.
supercall. Super must be called before accessing
thisin the constructor of a derived class.
abstractkeyword. Abstract classes are mainly for inheritance where other classes may derive from them. We cannot create an instance of an abstract class.
An abstract class typically includes one or more abstract methods or property declarations. The class which extends the abstract class must define all the abstract methods.
Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use.
They allow you to create reusable components (such as functions, classes, or interfaces) that can work with any data type while still providing type safety.
anyis certainly generic in that it will cause the function to accept any and all types for the type of arg, we actually are losing the information about what that type was when the function returns. If we passed in a number, the only information we have is that any type could be returned.
Instead, we need a way of capturing the type of the argument in such a way that we can also use it to denote what is being returned. Here, we will use a type variable, a special kind of variable that works on types rather than values.
Pair<T, U>, T and U are placeholders for the actual types that will be used when instances of Pair are created. This allows you to create instances of Pair with different types for the first and second properties without having to define a separate interface for each combination of types.
Type narrowing in TypeScript refers to the process of refining the type of a variable within a certain block of code based on certain conditions. This helps TypeScript infer more specific types, improving type safety and enabling better code optimization.
While it might not look like much, there’s actually a lot going on under the covers here. Much like how TypeScript analyzes runtime values using static types, it overlays type analysis on JavaScript’s runtime control flow constructs like if/else, conditional ternaries, loops, truthiness checks, etc., which can all affect those types.
inoperator
inoperator is used for type narrowing, which means it helps narrow down the type of an object, based on wether a property exists within it. It's particularly useful when working with union or discriminated types.
instanceofoperator
instanceofkeyword is used to check whether an object is an instance of a particular class or constructor function. It returns true if the object is an instance of the specified class or its subclasses; otherwise, it returns false.
A type predicate is a way to assert the type of a variable within a conditional statement. It allows you to narrow down the type of a variable within a certain block of code, based on some condition.
isFishfunction, we define a type predicate
pet is Fish, indicating that if the condition
(pet as Fish).swim !== undefinedis true, then pet is indeed a
Fish. Within the
feedPetfunction, when we call
isFish(pet), TypeScript narrows down the type of pet to Fish if the condition is met, allowing us to safely call
pet.swim()without TypeScript throwing errors.
kindin this case)
Exhaustive checking refers to ensuring that all possible cases of the discriminated union are handled within a switch statement or if-else chain. This helps TypeScript catch errors where you might forget to handle a specific case, ensuring that your code is more robust.
Thenevertype is used to indicate that a value should never occur. When used in the context of exhaustive checking with discriminated unions, it helps TypeScript ensure that all possible cases are handled, leaving no room for unexpected values.
Feel free to browse the repository, raise issues, share your feedback, and contribute to the project.