Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Kishimoto96/de3c668e440ff7306782433afeae7419 to your computer and use it in GitHub Desktop.
Save Kishimoto96/de3c668e440ff7306782433afeae7419 to your computer and use it in GitHub Desktop.
Discussion for Typescript

Typescript discussion

Write your answers in the comment section below:

  1. What are the primitive types in TypeScript?
  2. Explain how the arrays work in TypeScript.
  3. What is any type, and should we use it?
  4. How does enums work and how are they usefull?
  5. What is optional chaining and how does it work?
  6. "Javascript is dynamically typed" what does that mean? and how does Typescript affect that?
  7. What is the difference between Interface and Class?
  8. What is union and intersection type?
  9. Why to even bother with Typescript???
@Khaled6120
Copy link

Team members: Radman Lotfiazar, Harith Riyadh, Khaled Naes

  1. bigint, boolean, null, number, string, symbol,symbol

2.TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type.

3.Any is a data type in TypeScript. Any type is used when we deal with third-party programs and expect any variable but we don’t know the exact type of variable. Any data type is used because it helps in opt-in and opt-out of type checking during compilation.

  1. An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

5.The optional chaining operator (?.) enables you to
read the value of a property located deep within a
chain of connected objects without having to
check that each reference in the chain is valid.

The ?. operator is like the . chaining operator,
except that instead of causing an error if a reference
is nullish (null or undefined), the expression returns
a value of undefined.

6.Javascript is dynamically typed which means that it doesn't know the type of your variable until it instantiates it at run-time which can cause problems and errors in your projects
TypeScript, on the other hand, is a superset of JavaScript that introduces static typing. It allows developers to explicitly declare variable types during development and performs static type checking at compile-time. This means that TypeScript enforces stricter type rules and detects type-related errors before the code is executed, providing better reliability and tooling support compared to JavaScript's dynamic typing.

7.A class is a blueprint from which we can create objects that share the same configuration - properties and methods. An interface is a group of related properties and methods that describe an object, but neither provides implementation nor initialisation for them.

8.Defined in the Advanced Types section of Typescript, an intersection type is a type that combines several types into one; a value that can be any one of several types is a union type.

The & symbol is used to create an intersection, whereas the | symbol is used to represent a union. An intersection can be read as an And operator and a union as an Or.

9.TypeScript extends JavaScript and improves the developer experience. It enables developers to add type safety to their projects. Moreover, TypeScript provides various other features, like interfaces, type aliases, abstract classes, function overloading, tuple, generics, etc.

@nurabunamus
Copy link

Team members: Nur Abunamus - Atakan Serbes - Joud Khanji
1- boolean - true or false values.
number - whole numbers and floating point values.
string - text values like "TypeScript Rocks”.

2- An array declaration without the data type is deemed to be of the type any. The type of such an array is inferred from the data type of the array’s first element during initialization.
An array can also be created using the Array object. The Array constructor can be passed.

3- Any type in TypeScript is a generic type used when a variable’s type is unknown or when the variable’s type hasn’t yet been defined.
Any type should only be used when you don’t want to write a long type just to convince TypeScript that a piece of code is correct.

4- Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript.
Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

5- In TypeScript, optional chaining is defined as the ability to immediately stop running an expression if a part of it evaluates to either null or undefined. It was introduced in TypeScript 3.7 with the ?. operator.

6- JavaScript is dynamically typed, meaning variables can hold values of any type and their types can change at runtime. This flexibility can lead to potential errors and makes it challenging to catch type-related issues before executing the code.

TypeScript, a statically typed superset of JavaScript, brings static typing to the language. With TypeScript, you explicitly declare variable types, function parameters, and return types, enabling better code organization and documentation. TypeScript's static type checking occurs during compilation, catching potential type errors before runtime. This leads to improved code reliability, maintainability, and tooling support, such as autocompletion and code navigation.

7- Classes and interfaces are powerful structures that facilitate object-oriented programming and type-checking in TypeScript.
A class is a blueprint from which we can create objects that share the same configuration - properties and methods.
An interface is a group of related properties and methods that describe an object, but neither provides implementation nor initialization for them.

8 - Intersection and Union types are one of the ways in which you can compose types.
A union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type, so number | string | boolean is the type of a value that can be a number, a string, or a boolean
Intersection types are closely related to union types but are used very differently. An intersection type combines multiple types into one.

9 - Static typing – TypeScript comes with optional static typing and a type inference system, which means that a variable, declared with no type may be inferred by TypeScript based on its value.
We bother because of static typing

@sack-ali
Copy link

sack-ali commented Jun 6, 2023

@ozlemkeles , @nezirAydin , @baraah-berra. @sack_ali

1.There are 7 primitive data types:
string. number. bigint. boolean. undefined. symbol. null.
2- An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type. you can declare an array by specifying the type of its elements followed by square brackets [] or using the Array syntax.
3- The any type in TypeScript disables static type checking, allowing any value to be assigned to a variable. It reduces type safety and can lead to runtime errors. It's generally recommended to avoid using any whenever possible.
4- allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
5- Optional chaining is a TypeScript feature that allows you to safely access properties or call methods on objects that might be null or undefined. It uses the ?. operator to chain property or method access. If a property or method in the chain is null or undefined, the expression short-circuits and evaluates to undefined instead of throwing an error. Optional chaining helps prevent runtime errors when dealing with potentially non-existent properties or methods on objects.
6-In JavaScript, being dynamically typed means that variables are not bound to a specific type at compile-time or declaration-time. By adding static typing to JavaScript, TypeScript enhances the development experience, improves code quality, and enables better tooling support such as code editors with autocompletion, type inference, and refactoring capabilities.
7- Interfaces:

Used to define contracts for objects.
Describe the structure and behavior of objects.
Cannot have implementations or contain code.
Classes:

Used to create objects with specific properties and methods.
Provide implementation and can contain code.
Can be instantiated to create objects.
8- an intersection type is a type that combines several types into one; a value that can be any one of several types is a union type. The & symbol is used to create an intersection, whereas the | symbol is used to represent a union
9- TypeScript offers static typing, better tooling, and enhanced code maintainability compared to JavaScript. It catches errors early, improves collaboration, and scales well. TypeScript is compatible with JavaScript, has strong community support, and enables the use of future JavaScript features. It is valuable for large projects that require reliable and maintainable code.

@HishamWattar
Copy link

HishamWattar commented Jun 6, 2023

Members: @HishamWattar @handedemirbay @EdipNaser Baraah Almasri
1-TypeScript recognizes the following seven primitive types in JavaScript: bigint, Boolean, null, number, string, symbol, undefined
2-An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax like below :
a. Using square brackets. This method is similar to how you would declare arrays in JavaScript.
let fruits: string[] = ['Apple', 'Orange', 'Banana'];
b. Using a generic array type, Array.
let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];
3-The any type in TypeScript is a generic type used when a variable’s type is unknown or when the variable’s type hasn’t yet been defined,
the any type should only be used when you don’t want to write a long type just to convince TypeScript that a piece of code is correct.
4-Enums in TypeScript allow you to define a set of named values. They improve code readability, provide type safety, enable autocompletion and IDE support, and enhance code maintainability. Enums are useful when you want to represent a fixed set of related constants in your code.
5-The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null the expression short circuits and evaluates to [undefined] instead of throwing an error.
6-When you declare a variable, you do not need to specify what type this variable is. Javascript engine infers what type this variable is based on the value assigned to at run time.
7-A class is a blueprint from which we can create objects that share the same configuration - properties and methods. An interface is a group of related properties and methods that describe an object, but neither provides implementation nor initialization for them.
8-A union is a value that may have any of several representations or formats within the same position in memory; that consists of a variable that may hold such a data structure.
9-TypeScript is a superset of typed JavaScript (optional) that can help build and manage large-scale JavaScript projects. It can be considered JavaScript with additional features like strong static typing, compilation, and object-oriented programming

@Sara-Nefise
Copy link

Team Members: ahmad alashtar, @MOHAMMAD-ALMOHAMMAD, @saidbaradai, Sara Nafisa

  1. Primitive Types: String, Boolean, Number, Bigint, Null and Undefined, Symbol
  2. In TypeScript, arrays are used to store collections of elements of the same type. Arrays are similar to those in JavaScript but with the added benefit of static type checking provided by TypeScript. This means that you can specify the type of elements that an array can hold, and the TypeScript compiler will enforce that only elements of that type are added to the array.
  3. the any type is a special type that represents a value of any type. It essentially disables type checking for that particular value, allowing it to be assigned to variables of any type and to be used in any way without causing compile-time errors.
    While the any type provides flexibility, it also comes with some drawbacks: Loss of Type Safety, Lack of IDE Support, Increased Maintenance Effort.
  4. Enums define a set of named values, often referred to as members or elements, which represent a distinct set of possible values for a particular variable or property. Enums provide a way to create a collection of related constants and make your code more expressive and self-documenting.
    for example:
    enum Color {
    Red,
    Green,
    Blue
    }
    In this example, we define an enum called Color with three members: Red, Green, and Blue. By default, each member is assigned a numeric value starting from 0 and incremented by 1. Therefore, Color.Red has a value of 0, Color.Green has a value of 1, and Color.Blue has a value of 2. You can also explicitly assign values to enum members, for example:

enum Color {
Red = 1,
Green = 2,
Blue = 4
}
Overall, Enums offer improved code readability, type safety, and maintainability by enforcing a finite set of possible values for variables or properties.
5. Optional chaining allows you to safely access properties or call methods on a chain of potentially null or undefined values using the ?. operator, preventing runtime errors. If any part of the chain is null or undefined, the expression short-circuits and returns undefined.
6. In JavaScript, being dynamically typed means that variables can hold values of any type, and the type of a variable can be changed at runtime. This flexibility allows for greater freedom in writing code but can also lead to potential type-related errors that are only discovered at runtime.
TypeScript, on the other hand, is a superset of JavaScript that introduces static typing to the language. It enhances JavaScript by adding optional type annotations and compile-time type checking. With TypeScript, you can declare the types of variables, function parameters, and return values explicitly.
Early Error Detection
Enhanced Tooling Support
Improved Code Readability and Maintainability
7. Interfaces and classes are both important concepts in object-oriented programming, but they serve different purposes.
An interface is a contract that defines the structure of an object. It specifies the properties, methods, and events that an implementing class must have. However, interfaces themselves cannot provide any implementation details. They only define the shape or structure that a class should adhere to.
8. Union Types:Union types allow you to define a type that can hold values of multiple types. It is represented using the | operator
let variable: string | number; variable = "Hello"; // Valid variable = 10; // Valid variable = true; // Invalid, as boolean is not part of the union type
Intersection types allow you to combine multiple types into a single type that contains all the properties and methods of each type. It is represented using the & operator.
`interface Printable {
print(): void;
}

interface Loggable {
log(): void;
}

function createLogger(): Printable & Loggable {
return {
print() {
console.log("Printing...");
},
log() {
console.log("Logging...");
},
};
}

let logger = createLogger();
logger.print(); // Output: Printing...
logger.log(); // Output: Logging...
`
9. having types in code offers many benefits, including:

1- better readability
2- faster compilation time since there aren't any type conversions

@jimaa-maya
Copy link

Mustafa Noori, Mohamad Aid Bacuk Zanab, Jimaa Maya

1-There are 7 primitive data types:
string.
number.
bigint.
boolean.
undefined.
symbol.
null.

2-In TypeScript, arrays are a specific syntax for typing arrays. You can use the syntax number [] to specify the type of an array like [1, 2, 3], which works for any type (e.g. string [] is an array of strings, and so on). You may also see this written as Array, which means the same thing. TypeScript arrays are a data type just like a string, Boolean, and number. An array is a homogenous collection of similar type of elements which have a contiguous memory location. An array is a user-defined data type. An array is a type of data structure where we store the elements of a similar data type.

3-The any type in TypeScript is a generic type used when a variable's type is unknown or when the variable's type hasn't yet been defined. The any type is useful when converting existing JavaScript to TypeScript as it allows one to gradually opt-in and opt-out of type checking during compilation.

4-Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

5- Optional chaining is a feature in TypeScript that allows you to write code where TypeScript can immediately stop running some expressions if it runs into a null or undefined. The star of the show in optional chaining is the new ?. operator for optional property accesses. Optional chaining is the process of querying and invoking properties, subscripts, and methods on optional that may be nil. The ECMAScript feature allows developers to stop expressions from running if they find undefined or null values. Optional chaining will only take null or undefined as a signal to stop and return an undefined. Optional Element Access Property access is via the . operator, the optional chaining also works with the [] operators when accessing elements.

6- Dynamic typing in JavaScript means that when you declare a variable, you do not need to specify what type this variable is. The JavaScript engine infers what type this variable is based on the value assigned to it at runtime. TypeScript is a statically typed language that adds optional types to JavaScript. TypeScript is a superset of JavaScript that compiles to plain JavaScript. TypeScript adds optional types to JavaScript that can be checked at compile time. This means that TypeScript can catch errors before your code runs.

7- A class can contain data members and methods with the complete definition. An interface contains only the signature of members. A class can only be inherited from a single class but can be inherited from more than one interfaces. Interfaces are always implemented whereas classes are extended.

8- Union types and intersection types are used to compose or model types from existing types in TypeScript. Union types enable you to work with values that can be of multiple types, while intersection types allow you to combine multiple types into a single type. An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need.

9- There are two main reasons to use TypeScript. First, TypeScript adds a type system to help you avoid many problems with dynamic types in JavaScript. Second, TypeScript implements the future features of JavaScript a.k.a ES Next so that you can use them today. TypeScript simplifies JavaScript code, making it easier to read and debug. TypeScript provides highly productive development tools for JavaScript IDEs and practices, like static checking.

@abdulrahmanalbakkar
Copy link

Abdulrahman Albakkar, Tasneem Akkad, Bedreddin Naser, M. NOUR KRIMESH

There are 7 primitive data types:
string, number, bigint, boolean, undefined, symbol, null.

In TypeScript, arrays are similar to arrays in JavaScript but with the added benefit of static type checking. They are used to store multiple values of the same type sequentially. An array can contain elements of any valid TypeScript data type, such as numbers, strings, objects, or even other arrays.

In TypeScript, the 'any' type is a special type that represents a value of any type. When a variable is assigned the any type, it essentially means that the variable can hold values of any type, and TypeScript's static type checking is bypassed for that variable. However, the use of the 'any' type should generally be avoided whenever possible. TypeScript's main benefit lies in its strong static typing, which helps catch type errors at compile-time and provides better tooling support.

In TypeScript, an enum is a way to define a set of named values, where each value has a corresponding numeric or string representation. Enums provide a convenient way to work with a fixed set of values and make the code more readable and maintainable.

Optional chaining is a feature introduced in TypeScript (as well as in JavaScript) that provides a concise and safe way to access properties and methods of an object, even when intermediate properties may be null or undefined. It helps to avoid runtime errors that can occur when trying to access properties on nested objects that may be null or undefined.

The statement "JavaScript is dynamically typed" means that JavaScript does not enforce strict type checking at compile-time. In JavaScript, variables are not assigned specific types when they are declared. Instead, their types are determined dynamically at runtime based on the value they hold. TypeScript uses static type checking to analyze your code and catch type-related errors during development, before the code is executed.

Interfaces define contracts or blueprints that objects should follow, whereas classes provide the implementation and act as constructors for creating objects. Interfaces focus on structure and requirements, while classes encompass both structure and behavior.

Union and intersection types are powerful tools that allow you to create more flexible and expressive types in TypeScript. Union types enable handling multiple possible types, while intersection types facilitate combining properties and methods from different types. These features enhance type safety and flexibility in your code.

developers choose to use TypeScript because it offers:

  • Type safety: It catches type-related errors during development and provides more reliable code.
  • Enhanced tooling: TypeScript provides powerful IDE support with autocompletion and code navigation.
  • Code maintainability: TypeScript improves code organization and readability, making it easier to understand and maintain.
  • Collaboration: TypeScript's static types facilitate teamwork and reduce miscommunications.
  • ECMAScript compatibility: TypeScript supports the latest JavaScript features and can gradually introduce static typing.
  • Ecosystem and community: TypeScript has a thriving ecosystem and a supportive community.
  • Scalability: TypeScript is well-suited for large-scale applications, with features that enable robust codebases.

@0Rawan
Copy link

0Rawan commented Jun 6, 2023

Room #7 @AsliSema, @Gullied and @0Rawan
1.TypeScript recognizes the following seven primitive types in JavaScript:

bigint
boolean
null
number
string
symbol
undefined

  1. TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:

  2. Using square brackets. This method is similar to how you would declare arrays in JavaScript.

let fruits: string[] = ['Apple', 'Orange', 'Banana'];

  1. arrays are used to store multiple values of the same type. They provide a way to organize and manipulate collections of data. Arrays can contain elements of any valid TypeScript data type, including primitive types, objects, or even other arrays.
    Using a generic array type, Array.

let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];

Both methods produce the same output.

Of course, you can always initialize an array like the one shown below, but you will not get the advantage of TypeScript's type system.

let arr = [1, 3, 'Apple', 'Orange', 'Banana', true, false];

  1. any type in TypeScript is a generic type used when a variable's type is unknown or when the variable's type hasn't yet been defined. Any type is useful when converting existing JavaScript to TypeScript as it allows one to gradually opt in and opt-out of type checking during compilation.
  2. Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
  3. In TypeScript, optional chaining is defined as the ability to immediately stop running an expression if a part of it evaluates to either null or undefined
  4. Javascript is dynamically typed which means that it doesn’t know the type of your variable until it instantiates it at run-time which can cause problems and errors in your projects. Typescript adds static type support to Javascript, which takes care of bugs caused by false assumptions of a variable type if you use it correctly. You still have complete control over how strictly you type your code or if you even use types at all.
  5. . A class is a blueprint from which we can create objects that share the same configuration - properties and methods. An interface is a group of related properties and methods that describe an object, but neither provides implementation nor initialization for them.
  6. A union type allows a variable or parameter to have multiple possible types. It is denoted using the vertical bar (|) between the types.
    The union type represents the combination of all the specified types. The variable or parameter can hold a value that matches any of the specified types.

intersection type combines multiple types into a single type that has all the properties and methods of each constituent type. It is denoted using the ampersand (&) between the types.

The intersection type represents the merging of all the specified types. The resulting type must have all the properties and methods defined in each constituent type.
9. TypeScript is a superset of JavaScript. This means that:

It offers additional features to JavaScript such as static typing.
Using types is completely optional.
It compiles down to regular JavaScript.
It can be used for frontend JS as well as backend with Node.js.
It includes most features from ES6.
Types from third-party libraries can be added with type definitions.

Advantages of TypeScript
Makes your code more robust. All your variables can be defined with types.
Helps you easily spot bugs. Research says that 15% of commonly occurring bugs can be caught at compile time itself by TypeScript.
Improves predictability. If you've defined a variable to a string, it will stay a string.
Enhances readability. If you're working with multiple developers, TypeScript makes your code more expressive and self-explanatory and enforces a guideline to be followed by the team.
Growing popularity. As we discussed above, TypeScript is growing in popularity in the industry so it is a marketable skill to add to your resume.

@idincer944
Copy link

Members: @idincer944 İsmail Dincer | @masterofalune Ammar Almuain | Mahmoud Alshain | Rasam Rabiee

  1. String, Number(whole numbers and floating numbers) and Boolean. The difference is that you can force the type of the element in TypeScript.
  2. Apart from the forcing arrays are the same as they are in Javascript.

let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana'];
// or
let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];

  1. The any type in TypeScript is a generic type used when a variable's type is unknown or when the variable's type hasn't yet been defined.

  2. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

  3. Optional chaining is a feature in TypeScript that allows you to safely access properties and methods on an object, even if intermediate properties are null or undefined. It uses the ?. syntax and prevents runtime errors by evaluating to undefined if any intermediate property is missing.

6."JavaScript is dynamically typed" means that JavaScript does not require explicit type declarations for variables. You can assign values of any type to a variable without specifying the type beforehand. JavaScript determines the type of a value at runtime based on its assigned value or how it's used in the code.

  1. Interfaces define contracts that classes must adhere to, while classes provide the implementation details and serve as the building blocks for creating objects. Interfaces are useful for defining shared behavior and ensuring consistency across different classes, while classes define the specific structure, behavior, and state of objects.

8.Union Types:
A union type in TypeScript allows you to declare a variable that can hold values of different types. It is represented using the pipe (|) symbol between the types. For example, string | number denotes a type that can be either a string or a number. A variable with a union type can be assigned values of any of the specified types.

Intersection Types:
An intersection type in TypeScript allows you to combine multiple types into a single type. It is represented using the ampersand (&) symbol between the types. An object of an intersection type will have all the properties and methods from each of the intersected types. Intersection types are useful when you want to create a type that represents the combination of different types.

  1. TypeScript offers the benefits of static typing, improved code quality, enhanced tooling support, and better collaboration while still maintaining compatibility with JavaScript. It is particularly valuable for larger projects and teams where codebase maintenance, scalability, and error prevention are important considerations.

@OmarQaqish
Copy link

OmarQaqish commented Jun 6, 2023

@cansucreates @sheidanouri @OmarQaqish

  1. string, number, boolean, bigint, symbol, undefined, null.

  2. The syntax for arrays in TypeScript is again no different than JavaScript. However, typing becomes more important here. To declare an array of some type, we use the notation string[], number[], and so on. You can also use the syntax Array, Array, and so on. TypeScript will infer the type of an array if it is declared with some value initially. For example, we have an array of numbers below; TypeScript is smart enough to figure out that ids has the type number[]. const ids = [1, 2, 3];

  3. We can use any whenever we don't want a particular value to cause type-checking errors. It is useful when we don't want to write out a long type just to convince TypeScript that a particular line of code is okay. When a value is of type any, you can access any properties of it (which will, in turn, be of type any), call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal. It is generally considered a best practice to avoid using "any" whenever possible. This is because using "any" can make it easier to introduce errors into your code, as you lose the benefits of TypeScript's strong typing. Instead, it is recommended to use more specific data types whenever possible, as this helps catch errors early and provides better documentation for your code. For example, if you know that a variable will always be a string, it is better to declare it as type "string" rather than using "any".

  4. Enums are a feature added to JavaScript by TypeScript which allows for describing a value that could be one of a set of possible named constants. Unlike most TypeScript features, this is not a type-level addition to JavaScript but something added to the language and runtime. Because of this, it's a feature that you should know exists, but maybe hold off on using it unless you are sure.

enum Color {
Red,
Green,
Blue
}

Enums can make it easier to document intent, or create a set of distinct cases. Enums are often used in switch statements to check for corresponding values. Enums have a values () method, which returns an array of all enum constants.

  1. Optional chaining (?) is a feature introduced in TypeScript and JavaScript that allows you to safely access properties and methods of an object without causing an error if the property or method does not exist or is undefined or null. It provides a concise way to handle situations where you need to access nested properties or call methods on objects that may be null or undefined.

function printName(obj: { first: string; last?: string }) {
// ...
}

  1. In JavaScript, being dynamically typed means that variables are not bound to a specific type at compile-time or declaration. Instead, the types of variables and values are determined and checked at runtime. This allows for more flexibility in assigning different types of values to variables without explicit type annotations. TypeScript, on the other hand, is a superset of JavaScript that introduces static typing. It adds a layer of static type checking during development, allowing developers to specify and enforce types for variables, function parameters, and return values. TypeScript extends JavaScript by introducing type annotations, interfaces, enums, and other static type-related features.

  2. A class is a blueprint from which we can create objects that share the same configuration - properties and methods. An interface is a group of related properties and methods that describe an object, but neither provides implementation nor initialization for them. Interface is like a template that specifies what a class should be able to do, without dictating how it should be done. An interface can be implemented by any class, regardless of its inheritance hierarchy, allowing for greater flexibility and abstraction. In summary, while classes are used to define objects and their behavior, interfaces are used to define contracts that a class must fulfill in order to be considered a certain type.

@Younesnz
Copy link

Younesnz commented Jun 6, 2023

Group 10: @Younesnz , @Irzooqi , @fatimaali200

1-
image

2- it works like JS but we can also define a specific type or add some restrictions. for example:
if we have a single type: let fruits: string[] = ['Apple', 'Orange', 'Banana'];
if we have different types: let arr = [1, 3, 'Apple', 'Orange', 'Banana', true, false];

const names: readonly string[] = ["Dylan"]; names.push("Jack"); // Error: Property 'push' does not exist on type 'readonly string[]'.

3- Any type in TypeScript is a generic type used when a variable’s type is unknown or when the variable’s type hasn’t yet been defined.
Any type is useful when converting existing JavaScript to TypeScript as it allows one to gradually opt-in and opt-out of type checking during compilation.
it's not recommended to use any keyword in typescript because it can cause bugs.

4- An enum is a special "class" that represents a group of constants (unchangeable variables).
this is for Numeric Enum. it gives you the option of auto increment .
enum CardinalDirections { North = 1, East, South, West } // logs 1 console.log(CardinalDirections.North); // logs 4 console.log(CardinalDirections.West);

Here is the string enum example:
enum CardinalDirections { North = 'North', East = "East", South = "South", West = "West" }; // logs "North" console.log(CardinalDirections.North); // logs "West" console.log(CardinalDirections.West);

5- If you want to safely access the properties we can use ?. to prevent bugs. it will return undefined if the object hasn't got the property.

6-TypeScript can be strongly typed, while JavaScript is dynamically typed only. TypeScript is more readable and maintainable than JavaScript. TypeScript supports abstraction through interfaces, while JavaScript does not. TypeScript allows developers to annotate code with decorators, while JavaScript does not.

7- The main difference between class and interface is that a class describes the behavior of an object. In contrast, an interface contains the behaviors assigned and defined by the class

8- Defined in the Advanced Types section of Typescript, an intersection type is a type that combines several types into one; a value that can be any one of several types is a union type. The & symbol is used to create an intersection, whereas the | symbol is used to represent a union.

9-

  • Type safety: TypeScript is a statically typed language, which helps to prevent errors at runtime.
  • Better tooling: There are many tools available for TypeScript that make it easier to develop code, such as IDEs, linters, and debuggers.
  • Interoperability: TypeScript can be used to interoperate with JavaScript, which makes it a good choice for projects that need to be compatible with both TypeScript and JavaScript.
  • Reusability: TypeScript code can be reused in JavaScript projects, which makes it a good choice for libraries and frameworks.

@sncey
Copy link

sncey commented Jun 6, 2023

@Eng-NUREDDIN @tomiece317 @muhammedhasann

1- In TypeScript, the primitive types include:

number: Represents numeric values, including integers and floating-point numbers.
string: Represents textual data, such as a sequence of characters.
boolean: Represents a logical value, either true or false.
null: Represents the absence of any object value.
undefined: Represents an uninitialized or missing value.
symbol: Represents a unique identifier that is often used as a property key in objects.
bigint: Represents arbitrary precision integers (available starting from TypeScript 3.2).
These primitive types are used to define variables, function parameters, and return types in TypeScript.

2- Arrays in TypeScript are used to store collections of values of the same type. They can be declared using square brackets ([]) or the Array keyword. Arrays are zero-based and can be accessed using square bracket notation. TypeScript provides various built-in methods and properties to manipulate arrays. Type inference allows TypeScript to automatically infer the type of array elements, but you can also explicitly specify the type. Arrays are a flexible and powerful way to work with collections of data in TypeScript.
For example:
let numbers: number[] = [1, 2, 3, 4, 5]; let names: string[] = ["Alice", "Bob", "Charlie"];
Arrays can also be created using the Array constructor:
let numbers: Array<number> = new Array<number>(1, 2, 3, 4, 5); let names: Array<string> = new Array<string>("Alice", "Bob", "Charlie");
Arrays in TypeScript are zero-based, meaning the first element is accessed with an index of 0. You can access individual elements of an array using square bracket notation:
let numbers: number[] = [1, 2, 3, 4, 5]; let firstNumber: number = numbers[0]; // accessing the first element
Arrays have various built-in methods and properties that allow you to manipulate and work with the data they contain. Some commonly used array methods include push(), pop(), slice(), splice(), forEach(), and map().

TypeScript provides type inference for arrays, meaning that if you initialize an array with specific values, TypeScript can automatically infer the type of the array elements. However, you can also explicitly specify the type of the array elements to enforce type checking.

3- The any type in TypeScript allows values of any type, but its usage should be minimized. It bypasses type checking, reducing type safety and increasing the risk of errors. TypeScript's main advantage is static type checking, so it's better to use specific types for improved code reliability and maintainability.

4- Enums in TypeScript allow you to define a set of named constants with associated values. They enhance code readability and restrict variable values, improving clarity and catching errors at compile-time. Enums are useful for representing options, states, or predefined values in a type-safe manner.

Here's an example of a numeric enum:
`enum Direction {
North,
East,
South,
West
}

let myDirection: Direction = Direction.East;
console.log(myDirection); // Output: 1
And here's an example of a string enum:enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}

let myColor: Color = Color.Green;
console.log(myColor); // Output: "GREEN"
`
5- Optional chaining is a feature in TypeScript (and JavaScript) that allows you to safely access properties or call methods on potentially nullable objects. It helps prevent runtime errors by short-circuiting and returning undefined if the object is null or undefined. It provides a concise and convenient way to navigate object structures without explicit null checks.
6- JavaScript is dynamically typed, meaning variables can hold values of any type, and their types can change at runtime. TypeScript, a statically typed superset of JavaScript, introduces static type checking. It allows developers to specify types for variables, enabling early detection of type errors and enhancing code reliability and maintainability. TypeScript's static typing improves the development experience and catches errors before executing the code.

7- Interfaces define the structure and shape of objects without implementation details, ensuring consistency. Classes, on the other hand, allow object creation with defined behavior and state, encapsulating both data and behavior. Interfaces focus on enforcing contracts, while classes enable object instantiation and provide a blueprint for creating multiple instances with shared behavior.

8- Union types combine multiple types into one, allowing a variable to have more than one possible type (e.g., string | number). Intersection types combine multiple types into a single type that includes all their members (e.g., TypeA & TypeB). Union types provide flexibility, while intersection types allow for combining criteria and creating more specific types.

9- TypeScript provides type safety, enhanced tooling, improved maintainability, access to modern JavaScript features, a supportive community, and allows for gradual adoption. It improves code reliability and productivity, making it a valuable choice for developers.

@Rsmk-code
Copy link

@omikay @Rsmk-code @Abdulsalam Hanandoush @talal Bakkour

  1. In TypeScript, the primitive types include:
    number: Represents both integer and floating-point numbers.
    string: Represents textual data and is enclosed in single or double quotes.
    boolean: Represents a logical value, either true or false.
    null: Represents the absence of any object value.
    undefined: Represents an uninitialized variable.
    symbol: Represents a unique identifier.

  2. Arrays in TypeScript allow you to store multiple values of the same type. Arrays can be initialized using square brackets and can be accessed using zero-based indexing. TypeScript provides various array methods and properties to manipulate and work with arrays, such as push(), pop(), length, etc.

  3. The any type in TypeScript allows you to opt out of type checking for a particular variable or value. When a variable is assigned the any type, it essentially tells the TypeScript compiler to treat that value as having any type. While any provides flexibility, it bypasses type checking and can lead to potential runtime errors. It is generally recommended to avoid using any unless necessary.

  4. Enums in TypeScript allow a developer to define a set of named constants:
    With enums, you can create constants that you can easily relate to, making constants more legible.
    Developers have the freedom to create memory-efficient custom constants in JavaScript. JavaScript does not support enums, but TypeScript helps us access them.
    TypeScript enums save runtime and compile time with inline code in JavaScript.

enum Color {
  Red,
  Green,
  Blue
}
let myColor: Color = Color.Red;
  1. Optional chaining is a feature introduced in TypeScript that simplifies the process of accessing properties or calling methods on objects that may be null or undefined. It allows you to chain multiple property or method accesses with a question mark (?.) in between. If any part of the chain is null or undefined, the expression will short-circuit and evaluate to undefined. This helps avoid runtime errors when working with potentially nullable values.
interface Address {
  street: string;
  city?: string;
  country?: string;
}

interface Person {
  name: string;
  age: number;
  address?: Address;
}

const person: Person = {
  name: "John Doe",
  age: 25,
  // address is optional and not provided
};

// Accessing property using optional chaining
const city = person.address?.city;
console.log(city); // Output: undefined

// Accessing nested property using optional chaining
const country = person.address?.country;
console.log(country); // Output: undefined

// Calling method using optional chaining
const streetLength = person.address?.street.length;
console.log(streetLength); // Output: undefined
  1. Javascript being dynamically typed means that variable types are determined at runtime. Typescript, on the other hand, is a statically typed superset of Javascript that adds type annotations and allows for type checking at compile-time.

  2. An interface is a blueprint for defining the structure and behavior of an object, while a class is a template for creating objects with specific properties and methods.

  3. A union type combines multiple types into one, allowing a value to be of different types. An intersection type combines multiple types into one, representing a value that has all the properties of each type.

9.Typescript offers static type checking, which helps catch errors during development, improves code quality, and enhances tooling support like autocompletion and refactoring. It provides better code maintainability, scalability, and facilitates collaboration in larger codebases. Additionally, Typescript adds features like interfaces, enums, and decorators that enhance the development experience compared to plain JavaScript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment