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