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???
@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