Typescript Flashcards

1
Q

What is typescript

A

TypeScript is a superset of JavaScript, meaning that JavaScript code is valid TypeScript code. TypeScript adds rules about how values can be used but doesn’t consider JavaScript code to be in error based on syntax alone.

TypeScript is a typed superset, which means it introduces static typing rules. It helps catch type-related errors during development without changing the runtime behavior of JavaScript code.

When you move code from JavaScript to TypeScript, it guarantees the same runtime behavior. TypeScript preserves JavaScript’s behavior, ensuring your program runs the same way. This allows for an easy transition between the two languages without worrying about subtle differences.

By preserving JavaScript’s runtime behavior and providing static typing, TypeScript enhances development without introducing incompatible changes, making it a powerful and seamless extension of JavaScript.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

difference between typescript and javascript

A

TypeScript adds additional features and capabilities on top of JavaScript, such as static typing, interfaces, classes, modules, and more. By learning TypeScript, you will gain a deeper understanding of these advanced language features and how they can be utilized in your code.

TypeScript does introduce some additional syntax and concepts that are not present in JavaScript. This includes type annotations, TypeScript-specific decorators, and other language constructs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When should you use TypeScript?

A

When you have a large codebase

When your team’s developers are already accustom to statically-typed languages

If you or the majority of the team come from a strongly typed language like C# or Java, and don’t want to go all-in on JavaScript, TypeScript is a good alternative.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Simple types

A

Boolean: Represents the logical values true or false.

Number: Represents numeric values, including integers, floating-point numbers, and special numeric values like NaN and Infinity.

String: Represents textual data enclosed in single quotes (‘) or double quotes (“).

Null: Represents the intentional absence of any object value. It is a unique type that has only one possible value: null.

Undefined: Represents a variable that has been declared but has not been assigned any value yet. It is a type that has only one possible value: undefined.

Symbol: Represents unique and immutable values that can be used as property keys in objects.

BigInt: Represents arbitrary precision integers, enabling you to work with numbers larger than the maximum representable number in JavaScript’s Number type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

object types

A

In TypeScript, object types refer to types that represent structured objects with properties and methods:

Object Literal Type: You can define an object type using an object literal syntax, specifying the property names and their corresponding types. For example:

typescript
Copy code
let person: { name: string; age: number } = { name: “John”, age: 25 };

Interface: Interfaces are a powerful way to define object types in TypeScript. They allow you to specify the names, types, and optional/required status of properties, as well as define methods. For example:

typescript
Copy code
interface Person {
name: string;
age: number;
greet: () => void;
}

let person: Person = {
name: “John”,
age: 25,
greet: () => {
console.log(“Hello!”);
},
};

Class: Classes in TypeScript can be used to define object types with properties and methods. You can define a class with properties and member functions, and then create instances of that class. For example:

typescript
Copy code
class Person {
name: string;
age: number;

constructor(name: string, age: number) {
this.name = name;
this.age = age;
}

greet() {
console.log(“Hello!”);
}
}

let person: Person = new Person(“John”, 25);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

TypeScript has special types that may not refer to any specific type of data.

A

any is a type that disables type checking and effectively allows all types to be used.

unknown is a similar, but safer alternative to any.

typescript doesn’t allow you to use a variable of unknown type unless you either cast the variable to a known type or narrow its type
Type narrowing is the process of moving a less precise type to a more precise type.
The unknown type forces you to determine what a variable typed as unknown is, either through type casting or type narrowing.
This in turn leads to better programming, as typescript can then type check the resulting type, leading to a more type-safe program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Alias

A

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program.

Type aliases do not create new types. They simply provide a new name to an existing type.

The main purpose of type alias is to make our code more readable, and clearer in context for human understanding.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Interfaces

A

Interfaces in TypeScript define a contract or a blueprint for object structures. They allow you to specify the names, types, and optional/required status of properties, as well as define methods that should be implemented by objects that adhere to the interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

union type

A

Union types in TypeScript allow you to specify that a variable or parameter can hold values of different types. It provides flexibility by allowing a value to be of one type or another. Union types are denoted by using the pipe symbol (|) between the types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Tuple Types

A

A tuple is a TypeScript type that works like an array with some special considerations:

The number of elements of the array is fixed.
The type of the elements is known.
The type of the elements of the array need not be the same.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Enums

A

Enums in TypeScript are used to define a set of named constants, typically representing a specific set of related values. They provide a way to create more expressive and self-documenting code by assigning meaningful names to values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

numeric enums

A

Numeric enums in TypeScript are a type of enum where each member has an associated numeric value. By default, the values start from 0 and increment by 1 for each subsequent member. However, you can explicitly assign numeric values to the members if desire

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Array generics

A

Array generics in TypeScript allow you to define the type of elements that an array can hold. Generics provide a way to create reusable components or functions that can work with different types while maintaining type safety.

By using array generics, you can specify the type of elements that an array will contain, ensuring that only values of that specific type can be added to the array. This helps catch type errors at compile-time and provides better tooling support for autocompletion and type inference.

We can either use var or let for declaring an array.
The difference is var is used if we want the variable to be reflected/implemented throughout the program (global) and let for a specific block (local).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Typescript classes

A

TypeScript offers full support for the class keyword introduced in ES2015.
As with other JavaScript language features, TypeScript adds type annotations and other syntax to allow you to express relationships between classes and other types.
There are just a few differences between class constructor signatures and function signatures:
Constructors can’t have type parameters - these belong on the outer class declaration, which we’ll learn about later
Constructors can’t have return type annotations - the class instance type is always what’s returned
A function property on a class is called a method. Methods can use all the same type annotations as functions and constructors:
Other than the standard type annotations, TypeScript doesn’t add anything else new to methods.
Classes can also have accessors (getters/setters). TypeScript has some special inference rules for accessors:
If get exists but no set, the property is automatically readonly
If the type of the setter parameter is not specified, it is inferred from the return type of the getter
Getters and setters must have the same Member Visibility

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Describe Generics and generic classes

A

Generics in programming languages, including TypeScript, provide a way to create reusable components or functions that can work with different types while maintaining type safety. Generics allow you to define placeholders for types that are specified when the component or function is used, enabling flexibility and code reusability.

In TypeScript, generics can be used in various contexts, including functions, interfaces, and classes. When applied to classes, they are known as generic classes.

Generic Classes:
A generic class in TypeScript is a class that can work with multiple types. It allows you to define a class with one or more type parameters, which act as placeholders for the actual types used when creating instances of the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

TypeCasting

A

In TypeScript, you can use the as keyword or <> operator for type castings.

Type castings allow you to convert a variable from one type to another.

17
Q

Describe utility types

A

Utility types in TypeScript are pre-defined generic types provided by the language that offer helpful transformations or operations on other types. These utility types simplify common type manipulations, enhance type safety, and enable the creation of more expressive and reusable code.

Partial<Type>
Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.</Type>

Record<Keys, Type>
Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.

18
Q

Description for the KeyOf topic

A

The keyof keyword in TypeScript is used to create a type that represents the union of all keys of a given type. It allows you to extract the keys of an object or the names of properties of a class and use them as a type.

19
Q

Decorators in typescript

A

decorators in TypeScript are a language feature that allows you to add metadata and behavior to classes, methods, properties, or parameters at design time. They provide a way to modify the behavior of existing code without changing its implementation directly.

Decorators are declared using the @ symbol followed by the decorator function or class. They are applied to class declarations, method declarations, accessor declarations, property declarations, or parameter declarations. When the decorated code is executed, the decorator is invoked and can perform actions such as modifying the target object, adding additional functionality, or applying transformations.

20
Q

Functions in typescript

A

Functions are the basic building block of any application, whether they’re local functions, imported from another module, or methods on a class.
A function is a set of statements to perform a specific task.
Functions organize the program into logical blocks of code.
Once defined, functions may be called to access code. This makes the code reusable.
Moreover, functions make it easy to read and maintain the program’s code.
They’re also values, and just like other values, TypeScript has many ways to describe how functions can be called.

21
Q

Cumulative for the as Const

A

The as const assertion in TypeScript is used to tell the compiler that a value should be treated as a readonly or constant value, with its literal type preserved. It is typically used in situations where you want to enforce immutability and ensure that the assigned value cannot be modified or narrowed down to a narrower type.

22
Q

What are typeguards

A

Type guards in TypeScript are a way to narrow down the type of a variable or value within a conditional block. They provide a mechanism to make more specific type inferences based on runtime checks, allowing you to write code that handles different types differently.

Type guards allow you to write more type-safe code by narrowing down the possible types of a variable within a specific code block. This helps you avoid type errors and enables the TypeScript compiler to provide better type inference and checking. Type guards are especially useful when working with union types or when you need to handle different types differently based on runtime conditions.

typeof Type Guard:

Uses the typeof operator to narrow down the type based on the runtime type of the value.
Example: typeof value === “string”

instanceof Type Guard:

Checks if the value is an instance of a specific class or constructor function.
Example: value instanceof MyClass

Custom Type Guards:

User-defined functions that perform runtime checks and return a type predicate.
The return type of the function is used as a type predicate to narrow down the type.
Example: function isString(value: any): value is string

23
Q

Compare and contrast interface vs. type.

A

Interface and type are both used in TypeScript to define the shape and structure of objects, but they have some differences in terms of their usage and capabilities.

Interface:

Interfaces are a way to define contracts for objects, specifying the properties and methods that an object must have.
They can be used to describe the shape of objects, classes, and function types.
Interfaces can be extended to inherit properties and methods from other interfaces using the extends keyword.
They can also be implemented by classes to enforce that the class adheres to the contract defined by the interface.
Interfaces can be merged together if they have the same name, allowing you to split the definition across multiple files.
Interfaces support declaration merging, enabling you to add new properties or methods to an existing interface.
Type:

Types allow you to create aliases for existing types or create new types from scratch.
They can represent primitive types, union types, intersection types, tuples, and more.
Types are flexible and powerful, allowing you to perform complex type transformations and manipulations.
They can be used to define the shape of objects, as well as function types and other custom types.
Types can be combined using union (|) and intersection (&) operators to create more complex types.
Types support conditional types, mapped types, and other advanced type operations.
In general, interfaces are commonly used when defining the structure of objects or classes and enforcing contracts, while types are used for creating custom types, combining existing types, or performing more advanced type manipulations.

It’s important to note that the decision to use interfaces or types often comes down to personal preference or project conventions. Both interfaces and types are powerful features of TypeScript that help in creating well-typed and maintainable code.

24
Q

Describe the Readonly interface

A

The Readonly interface is a built-in utility interface provided by TypeScript. It is used to create read-only versions of object types, which means that once an object is assigned a type with Readonly, its properties cannot be modified. This provides immutability for objects, preventing accidental changes to their properties.

The Readonly interface is primarily used to ensure that certain data remains unchanged throughout the program execution. It can be applied to object types, array types, and tuple types.