Typescript Flashcards
TypeScript
TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. TypeScript is pure object oriented with classes, interfaces and statically typed like C# or Java.
TypeScript is a strongly typed, object oriented, compiled language. It was designed by Anders Hejlsberg (designer of C#) at Microsoft.
Declaration Files
When a TypeScript script gets compiled, there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript.
Compiler flag & Description
- –help
Displays the help manual - –module
Load external modules - –target
Set the target ECMA version - –declaration
Generates an additional .d.ts file - –removeComments
Removes all comments from the output file - –out
Compile multiple files into a single output file - –sourcemap
Generate a sourcemap (.map) files - –module noImplicitAny
Disallows the compiler from inferring the any type - –watch
Watch for file changes and recompile them on the fly
Type Guards
Type guards allow you to get the type of variables. After that, you can perform multiple operations based on the type of the particular variables. This also ensures the type-safety.
is
typeof
The never type
The never type in TypeScript represents the values that can never occur. For example, the return type of a function that throws an error is never.
function funcName(): never{
// it throws an exception or never returns
}
void vs. never
In TypeScript, a variable of void type can store undefined as a value.
On the other hand, never can’t store any value.
let val1: void = undefined;
let val2: never = undefined; // error: Type ‘undefined’ is not assignable to type ‘never’.
Union
Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars
let value: number | string | boolean;
There are three types of the literal types in TypeScript.
String literal types
Numeric literal types
Boolean literal types
Symbols
In TypeScript, a symbol is a primitive data type that is unique and immutable. The symbols are introduced in ECMAScript 2015 (also known as ES6).
As we use the number, string, or boolean to create the variables of different data-type, we can use the symbol type to create the Symbol.
Symbols are unique and immutable
null vs. undefined
null:
Has its own type null
Must be handled explicitly in logic to avoid errors
undefined:
Triggers default function parameters
Indicates missing parameters or optional parameters
Type Aliases
In TypeScript, type aliases is a way to define a type. It allows you to give a specific name to the type or define a custom type using the ‘type’ keyword.
type StringOrNumber = string | number;
Aliasing Tuples
The tuple alias is used to define the structure of the fixed-size array, which can contain specific types of values in a particular order.
Optional Parameters
function functionName(para1:type1, para2?:type2): returnType{
// function body
}
Extending Interfaces
One interesting feature of interfaces is the ability to extend them, allowing us to create a combination of interfaces. Extending an interface is also known as interface inheritance.
Use extends keyword to extend a single or multiple interfaces in TypeScript.
Access Modifiers
Public:
The public members are accessible from anywhere within and outside the class that defines the member.
Private Access Modifiers:
A private access modifier restricts the access of ** the class member (property or method) to the class where it is declared.** When you add the private modifier to the property or method, you can access that property or method within the same class only.
Protected Access Modifiers:
The protected access modifier is used to define a protected class member (property or method). A protected data member ** is accessible only within the class that defines it or any class that extends it.**
TypeScript - Readonly Properties
TypeScript provides us with readonly keyword to make a property in class, type or interface as read-only. The readonly properties can be accessed outside the class but their values can’t be modified.
Abstraction Classes
The abstract classes are used to achieve abstraction in TypeScript. The abstract class contains only method declaration but not implementation.
We need to implement all abstract methods of the abstract class into the inherited class.
The abstraction is a way to hide the lower-level code implementation from users and some developers.
Furthermore, it is used to show only the required information about the method rather than showing the whole complex implementation of methods.
Duck Typing
The circumstance where an object’s type is decided by its behavior, like methods and attributes, rather than its class is known as “duck typing”.
Intersection Types
In TypeScript, an intersection type combines multiple types into one. Although intersection and union types in TypeScript are similar, they are used in very different ways.
type intersepted_Type = Type1 & Type2;
Type Assertions
Type assertion is a mechanism in TypeScript that informs the compiler of the variable type
Using as operator
Using <> operator
Using object
Generics
Generics are a powerful feature in TypeScript that allow you to write reusable code that can work with different types of data. They act like placeholders that can be filled with specific data types when you use the generic code. This improves code flexibility and maintainability.
Namespace
A namespace is a way to logically group related code. This is inbuilt into TypeScript unlike in JavaScript where variables declarations go into a global scope and if multiple JavaScript files are used within same project there will be possibility of overwriting or misconstruing the same variables, which will lead to the “global namespace pollution problem” in JavaScript.
Modules
A module is designed with the idea to organize code written in TypeScript.** Modules are broadly divided into −**
Internal Modules
External Modules
Ambients
Ambient declarations are a way of telling the TypeScript compiler that the actual source code exists elsewhere. When you are consuming a bunch of third party js libraries like jquery/angularjs/nodejs you can’t rewrite it in TypeScript. Ensuring typesafety and intellisense while using these libraries will be challenging for a TypeScript programmer. Ambient declarations help to seamlessly integrate other js libraries into TypeScript.
Decorators
Decorators in TypeScript are special kinds of declarations that can be attached to the class declaration, property, accessor, method, and parameters.
**It is used for the separate modification of the class without modifying the original source code. **This makes them a powerful tool in the domain of object-oriented programming, allowing you to write cleaner, more organized code that adheres to the DRY (Don’t Repeat Yourself) principle.
Mixins
In TypeScript, mixins is a concept that allows us to extend a single class via multiple classes. This way, we can reuse the class components and combine their methods and properties in a single class.
Utility Types
The Partial utility type transforms all the properties of the current type to optional. The meaning of the partial is either all, some, or none. So, it makes all properties optional, and users can use it while refactoring the code with objects.
Boxing
Boxing is the process of wrapping a value type in an object type. In contrast, unboxing is the process of unwrapping an object type back to a value type.
tsconfig.json
The TypeScript tsconfig.json file is a configuration file to specify the compiler options. These compiler options are used to compile the TypeScript code and convert it into JavaScript code.
compileOnSave
compilerOptions
files
include
exclude
Runtime Behavior of typescript
TypeScript is also a programming language that preserves the runtime behavior of JavaScript.
For example, dividing by zero in JavaScript produces Infinity instead of throwing a runtime exception. As a principle, TypeScript never changes the runtime behavior of JavaScript code.
This means that if you move code from JavaScript to TypeScript, it is guaranteed to run the same way, even if TypeScript thinks that the code has type errors.
Erased Types
Roughly speaking, once TypeScript’s compiler is done with checking your code, it erases the types to produce the resulting “compiled” code. This means that once your code is compiled, the resulting plain JS code has no type information.
This also means that TypeScript never changes the behavior of your program based on the types it inferred. The bottom line is that while you might see type errors during compilation, the type system itself has no bearing on how your program works when it runs.
Short for typescript
TypeScript is JavaScript’s runtime with a compile-time type checker.
Explicit Types
We tell the program what is the type
Differences Between Type Aliases and Interfaces
Type aliases and interfaces are very similar, and in many cases you can choose between them freely. Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable
extending:
Extending a type via intersections
Extending interface through extends
adding field:
Adding new fields to an existing interface- just the same as parent
A type cannot be changed after being created
A TYPE CANNOT BE CHANGED AFTER BEING CREATED!
Type Assertions
Sometimes you will have information about the type of a value that TypeScript can’t know about.
In this situation, you can use a type assertion to specify a more specific type:
as HTMLCanvasElement;
using <> or as
The developer knows what type the value is
Non-null Assertion Operator (Postfix !)
TypeScript also has a special syntax for removing null and undefined from a type without doing any explicit checking. Writing ! after any expression is effectively a type assertion that the value isn’t null or undefined:
The developer says: trust me, it wont be null
Enums
Enums are a feature added to JavaScript by TypeScript which allows for describing a value which could be one of a set of possible named constants.
Primitive types
string,
number,
boolean,
bigint,
symbol
SSBBN
typeof- type guards return types
“string”
“number”
“bigint”
“boolean”
“symbol”
“undefined”
“object”
“function”
Falsy values
0
NaN
“” (the empty string)
0n (the bigint version of zero)
null
undefined
The in operator narrowing
Helps to check, if a key exists in object
Instanceof vs typeof
Use instanceof for custom types
Use typeof for simple built in types
Operator instanceof sprawdza, czy dany obiekt jest instancją określonego typu (konstruktora). Innymi słowy – analizuje łańcuch prototypów (prototype chain) i sprawdza, czy dany obiekt został utworzony danym konstruktorem.
Operator typeof zwraca typ obiektu; sprawdza, czy dany obiekt jest typu prymitywnego (prostego), czy jest czymkolwiek innym (obiektem).
is in functions
we take any value, check if the value is a type of and then return a value
Function Overloads
Some JavaScript functions can be called in a variety of argument counts and types. For example, you might write a function to produce a Date that takes either a timestamp (one argument) or a month/day/year specification (three arguments).
In TypeScript, we can specify a function that can be called in different ways by writing overload signatures. To do this, write some number of function signatures (usually two or more), followed by the body of the function:
same function name, different constructor
Rest Parameters and Arguments
In addition to using optional parameters or overloads to make functions that can accept a variety of fixed argument counts, we can also define functions that take an unbounded number of arguments using rest parameters.
we can have as many parameters as we want
ReadonlyArray
The ReadonlyArray is a special type that describes arrays that shouldn’t be changed.
Tuple Types
A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions.
Decorators
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.
Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
JSX
JSX is an embeddable XML-like syntax. It is meant to be transformed into valid JavaScript, though the semantics of that transformation are implementation-specific. JSX rose to popularity with the React framework, but has since seen other implementations as well. TypeScript supports embedding, type checking, and compiling JSX directly to JavaScript.