Skip to content

Instantly share code, notes, and snippets.

@halitbatur
Created June 28, 2022 11:17
Show Gist options
  • Save halitbatur/d9aee04b6f0e75c85966c74ba26db0a4 to your computer and use it in GitHub Desktop.
Save halitbatur/d9aee04b6f0e75c85966c74ba26db0a4 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???
@irem-kurt
Copy link

@yamanrajab90
Copy link

yamanrajab90 commented Jun 28, 2022

Members: Nilay, Rasha, Yaman.

  1. What are the primitive types in TypeScript?
    Numbers - Integers, floats
    Strings - Any data under single quote, double-quote or backtick quote
    Booleans - true or false value
    Null - empty value or no value
    Undefined - a declared variable without a value
    Symbol - A unique value that can be generated by the Symbol constructor.

  1. Explain how the arrays work in TypeScript.
    TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:

  2. Using square brackets. let fruits: string[] = ['Apple', 'Orange', 'Banana'];

  3. Using a generic array type. let fruits: Array<string> = ['Apple', 'Orange', 'Banana'];

  • Arrays can contain elements of any data type, numbers, strings, or even objects.

  • Arrays can be declared and initialized separately.

  • An array in TypeScript can contain elements of different data types using a generic array type syntax.

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

  1. What is any type, and should we use it?
    Typescript allows us to opt out of type checking by assigning any type to a variable. The compiler will not perform type checking on variables whose type is any.
    any is a special data type that can hold any data. You can change the data type. We use this when we do not know the type of data.

  1. How do enums work and how are they useful?
    TypeScript enums allow us to define or declare a set of named constants i.e. a collection of related values which could either be in the form of a string or number or any other data type. Enums provides a great way to organize the code in TypeScript. Enums save compile-time and runtime with inline code in JavaScript. Enums allow for the creation of memory-efficient custom constants in JavaScript. Enums generally accept default values in numbers (starting from 0).
    Although a user could change the values provided in enums according to the requirements. Values inside enums are marked as constants so they can also be accessed but they can’t be altered or changed. The output of a TypeScript enum is an object which we have seen in JavaScript (although JavaScript doesn’t support enums). This object consists of named properties declared in the enum. This object also has number keys with string values representing the named constants. That’s why we may pass a number into a function that accepts an enum. In other words, we may also visualize enum members as both a number and a defined constant.

  1. What is optional chaining and how does it work?
    TypeScript Optional Chaining is the process of searching and calling variables, methods, and parameters that might be nil in existence. This particular feature allows the developers to stop encountering the errors which generally come up if things are not defined, and also they could easily handle the undefined things with this particular feature. Optional Chaining actually works in a bit of a tricky manner, wherein it first checks the availability of a particular variable or a function. If that variable or function is available in the file, then it proceeds with checking the further mentioned variable or function. If that variable is not available, it immediately stops checking further and returns “undefined” which a user could easily handle with certain logic.

6- " Javascript is dynamically typed" what does that mean? and how does Typescript affect that?

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 our projects. Typescript adds static type support to Javascript which takes care of bugs that are caused by the false assumptions of a variable type if we use it right. We still have full control over how strict we type our code or if we even use types at all.

7-What is the difference between Interface and Class?
A class describes the attributes and behaviors of an object.
An interface contains behaviors that a class implements.


  1. What is union and intersection type?
    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.

  1. Why to even bother with Typescript???
    This enables developers to evade errors and do rewrites much easier. Types invalidate most of the silly errors that can sneak into JavaScript codebases, and create a quick feedback loop to fix all the little mistakes when writing new code and refactoring

@cbaksakal
Copy link

Team: Melek, Huzeyfe, Cengiz

What are the primitive types in TypeScript?
number , string , boolean , bigint , symbol , undefined , and null

Explain how the arrays work in TypeScript.

  1. Using square brackets. This method is similar to how you would declare arrays in JavaScript.
    let fruits: string[] = ['Apple', 'Orange', 'Banana'];

  2. Using a generic array type, Array.
    let fruits: Array = ['Apple', 'Orange', 'Banana'];

Both methods produce the same output.

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

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

In this type of array creation, type of the array becomes "any".

What is any type, and should we use it?
The TypeScript any type allows you to store a value of any type. It instructs the compiler to skip type checking.
Use the any type to store a value that you don’t actually know its type at the compile-time or when you migrate a JavaScript project over to a TypeScript project.

Beginners of TypeScript are often tempted to use any type, but it is highly discouraged. It is possible in almost all cases to write code without any. Do not use any as a crutch to skip past type errors: doing so is often a sign that something else is wrong with the code (and any is simply being used to ignore the fundamental issue).

How does enums work and how are they usefull?
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.

What is optional chaining and how does it work?
At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined. The star of the show in optional chaining is the new ?. operator for optional property accesses. When we write code like

let x = foo?.bar.baz();
this is a way of saying that when foo is defined, foo.bar.baz() will be computed; but when foo is null or undefined, stop what we’re doing and just return undefined.”

"Javascript is dynamically typed" what does that mean? and how does Typescript affect that?
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.

In dynamically typed languages, the types are associated with run-time values and not named explicitly in your code. For example, JavaScript, Python, Ruby, and PHP.

JavaScript is a dynamically typed and interpreted programming language. In general, both of these mean that little preprocessing is done before running JavaScript code. When we say JavaScript is dynamically typed, it means that JavaScript variables have types, such as string, boolean, and number, but these are determined at the time that the code is run -- not beforehand. As an interpreted programming language, the source code is not preprocessed, and code is interpreted, or executed, from human-readable code to things that the machine understands at the time that it runs. You may have noticed that there is an error with types in your JavaScript code -- say you tried to add an array and a number together -- this error will not be caught until the time that the code is run. This is a consequence of being both dynamically typed and interpreted; we are allowed to add together two types that don't make sense (what does it mean to add a list to a number?) and the error only appears if we run the code.

What is the difference between Interface and Class?
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.

Class
TypeScript is an object-oriented JavaScript language, which supports programming features like classes, interfaces, polymorphism, data-binding, etc. TypeScript support these features from ES6 and later version.

Classes are the fundamental entities which are used to create reusable components. It is a group of objects which have common properties. In terms of OOPs, a class is a template or blueprint for creating objects. It is a logical entity.

Interface
An Interface is a structure which acts as a contract in our application. It defines the syntax for classes to follow, means a class which implements an interface is bound to implement all its members. We cannot instantiate the interface, but it can be referenced by the class object that implements it.

The interface contains only the declaration of the methods and fields, but not the implementation. We cannot use it to build anything. A class inherits an interface, and the class which implements interface defines all members of the interface.

When the Typescript compiler compiles it into JavaScript, then the interface will be removed from the JavaScript file. Thus, its purpose is to help in the development stage only.

What is union and intersection type?
An intersection type combines multiple types into one.
A union type describes a value that can be one of several types.
Usage and notation are quite simple, the & symbol is used to build an intersection while the | symbol is for union.

Why to even bother with Typescript???
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.

Why Should We Use TypeScript?

  • TypeScript simplifies JavaScript code, making it easier to read and debug.
  • TypeScript is open source.
  • TypeScript provides highly productive development tools for JavaScript IDEs and practices, like static checking.
  • TypeScript makes code easier to read and understand.
  • With TypeScript, we can make a huge improvement over plain JavaScript.
  • TypeScript gives us all the benefits of ES6 (ECMAScript 6), plus more productivity.
  • TypeScript can help us to avoid painful bugs that developers commonly run into when writing JavaScript by type checking the code.
  • Powerful type system, including generics.
  • TypeScript is nothing but JavaScript with some additional features.
  • Structural, rather than nominal.
  • TypeScript code can be compiled as per ES5 and ES6 standards to support the latest browser.
  • Aligned with ECMAScript for compatibility.
  • Starts and ends with JavaScript.
  • Supports static typing.
  • TypeScript will save developers time.
  • TypeScript is a superset of ES3, ES5, and ES6.

References:

@abdulhafiz96
Copy link

Hafiz-Hamza-Sobhan

1- number, string, boolean, null type, undefined, bigInt and symbol

2- In TypeScript, an array is an ordered list of values. An array can store a mixed type of values.
To declare an array of a specific type, you use the let arr: type[] syntax.
If one type has been declared then only this type is accepted inside the array as an element.

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. it is used because it helps in opt-in and opt-out of type checking during compilation.

4- In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values. One common example is the suit value of a single card in a deck of playing cards. Every card that is drawn will either be a club, a diamond, a heart, or a spade; there are no possible suit values beyond these four, and these possible values are not likely to change. Because of this, an enum would be an efficient and clear way to describe the possible suits of a card.

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., and if we tried to access a property that does not exists in the object with the “.” it will cause an error, but if we used an optional chaining it will give us undeifend instead of an error

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 adds static type support to Javascript which takes care of bugs that are caused by false assumption of a variable type if you use it right. You still have full control over how strict you type your code or if you even use types at all.

7-Classes are the fundamental entities which are used to create reusable components. It is a group of objects which have common properties. In terms of OOPs, a class is a template or blueprint for creating objects. It is a logical entity.
An Interface is a structure which acts as a contract in our application. It defines the syntax for classes to follow, means a class which implements an interface is bound to implement all its members. We cannot instantiate the interface, but it can be referenced by the class object that implements it.
The interface contains only the declaration of the methods and fields, but not the implementation

8-
union type variable is a variable which can store multiple type of values (i.e. number, string etc). A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ( '|' ) symbol between the types like -> const x : number | string = 1 or ‘hello’ both valid ,

An intersection type creates a new type by combining multiple existing types. The new type has all features of the existing types. To combine types, you use the & sign

9-In contrast to JavaScript, TypeScript code is more reliable and easier to refactor. This enables developers to evade errors and do rewrites much easier.
Types invalidate most of the silly errors that can sneak into JavaScript codebases, and create a quick feedback loop to fix all the little mistakes when writing new code and refactoring,TypeScript is more explicit : Making types explicit focuses our attention on how exactly our system is built, and how different parts of it interact with each other.

@halakhellow
Copy link

berk akipek, mehmet baki, mohammad sheikh ibrahim, hala alkhellow

https://docs.google.com/document/d/1sUmQKaqIlQ1qZNvRldH3Vi2T9tAOHv7zDeaagRshNlw/edit#

@khatibAmjad
Copy link

team: emine - amjad

What are the primitive types in TypeScript?
Number – String – Boolean

Explain how the arrays work in TypeScript.
TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:

  1. Using square brackets. This method is similar to how you would declare arrays in JavaScript.
    let fruits: string[] = ['Apple', 'Orange', 'Banana'];
  2. Using a generic array type, Array.
    let fruits: Array = ['Apple', 'Orange', 'Banana'];
    One can set the type of array to “any” in order to create an array of mixed types, that’s discouraged though. There’s a way to set a specific pattern of types inside an array, it’s called Tuples. And it’s done like this:
    let fruits: [string, number] = ['Apple', 1];
    let fruits: [string, number][] = [['Apple', 1], [orange, 2]] ;
    in the above examples the first element should always be a string whereas the second element should always be a number.

What is any type, and should we use it?
Any is a type we can set variables to when we don’t want to be strict about their types. Using any defies the purpose of using typescript and it undermines the type-safety feature of typescript, so it’s better not to use it.

How does enums work and how are they usefull?
Enums allow for describing a value that could be one of a set of possible named constants.
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.

What is optional chaining and how does it work?
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

"Javascript is dynamically typed" what does that mean? and how does Typescript affect that?
When working with JS upon declaring a new variable you assign it a value, at first, the data type of the variable could be a number, then a string when the value 'hello' can be assigned to it, and then a boolean when true is assigned to it. So all these types are determined at the runtime. That’s what is called a dynamically typed language. The types of the variables are determined while compiling the code.
TypeScript prevents assigning values of different types to a declared variable with a certain type.

What is the difference between Interface and Class?

Classes are the fundamental entities used to create reusable components. It is a group of objects which have common properties. It can contain properties like fields, methods, constructors, etc. used for object creation, encapsulation for fields, methods.

An class can be instantiated.The member of a class can be public, protected, or private.A class can extend only one class and can implement any number of the interface.

An Interface defines a structure which acts as a contract in our application. It contains only the declaration of the methods and fields, but not the implementation.
It is used to create a structure for an entity.Interface completely disappeared during the compilation of code.An interface cannot be instantiated.The members of an interface are always public.An interface can extend more than one interfaces but cannot implement any interface.

What is union and intersection type?
A union type is a type formed from two or more other types, representing values that may be any one of those types. We refer to each of these types as the union's members.
let id: string | number;
// This is valid
id = 22;
// This is also valid
id = "22";

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

interface ErrorHandling {
success: boolean;
error?: { message: string };
}

interface ArtworksData {
artworks: { title: string }[];
}

interface ArtistsData {
artists: { name: string }[];
}

// These interfaces are composed to have
// consistent error handling, and their own data.

type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;

Why to even bother with Typescript???

Optional static typing. JavaScript is a dynamically typed language, which means that types are checked, and data type errors are only detected at runtime. This can be very dangerous and can create errors during production. TypeScript introduces optional strong static typing: once declared, a variable does not change its type and can only take specific values.
TypeScript supports Object-Oriented Programming (OOP) concepts such as classes, interfaces, inheritance, etc. The OOP paradigm makes it easier to build well-organized scalable code, and this advantage becomes more apparent as your project grows in size and complexity

@khaldarov
Copy link

khaldarov commented Jun 28, 2022

Noor Awied, Lara Gurol, Adnan Khaldar

What are the primitive types in TypeScript?

​​Number, string, tuple, enum, unknown, any, void, never, boolean, null, and undefined types

Explain how the arrays work in TypeScript.

Generic type: let fruits: Array<string>
Specific type: let fruits: string[ ]
For arrays with more than one type: let values: Array<string | number>

What is any type, and should we use it?

It allows you to store a value of any type. 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.
Since we typed any data type to temp, it expects all types of data-type and doesn’t give any error.

How does enums work, and how are they useful?

Although enum is a reserved word in JavaScript, JavaScript has no support for traditional enums. However, it is fairly easy to define enums using objects in JavaScript. For example, TypeScript has support for enums:

enum Direction { Up, Down, Left, Right }

At runtime, TypeScript compiles the above code into the below enum-like object:

const Direction = { Up: 'Up', Down: 'Down', Left: 'Left', Right: 'Right' };

This object has most of the features that you would expect from an enum:
Get all allowed enum values: Object.keys(Direction) returns an array ['Up', 'Down', 'Left', 'Right']
Check if a value equals an enum value: val === Direction.Up
Check if a value is in the enum: Direction.hasOwnProperty('Up')
However, there are a couple of limitations:
You can modify the enum after instantiation. For example, Direction.sideways = 'sideways'.
If val === undefined, then val === Direction.notAnEnumValue and val === Direction.Downe. So typos in enum properties can cause issues.
No guarantee that property values don't conflict. Direction.Down = 'Up' is valid.

What is optional chaining, and how does it work?

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.
Ex: const dogName = adventurer.dog?.name;
The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

"JavaScript is dynamically typed" what does that mean, and how does Typescript affect that?

TypeScript offers a flexible and forgiving environment for writing code and script, and it’s a lightweight language, so you won’t get bogged down by excess syntax and features, and you don't know the type of your variables until run-time, so you may encounter errors or problems. When Typescript is used properly, it fixes bugs caused by false assumptions about variable types in JavaScript.

What is the difference between Interface and Class?

Classes are the fundamental entities used to create reusable components. It is a group of objects which have common properties. It can contain properties like fields, methods, constructors, etc. We use classes as object factories. A class defines a blueprint of what an object should look like and act like, and then implements that blueprint by initializing class properties and defining methods. Therefore, when we create an instance of the class, we get an object that has actionable functions and defined properties.
An Interface defines a structure which acts as a contract in our application. An interface is simply a structural contract that defines what the properties of an object should have as a name and as a type.

What is union and intersection type?

An intersection type combines multiple types into one. A union type describes a value that can be one of several types. Usage and notation are quite simple, the & symbol is used to build an intersection while the | symbol is for union.

Why to even bother with Typescript???

Advanced type system (Optional static typing)

TypeScript could be used for detecting errors before runtime, making our projects less prone to errors.

Readability

Thanks to the addition of strict types and other elements that make the code more self-expressive, you can see the design intent of the developers who originally wrote the code.

Typing support

Type information renders editors and IDEs much more useful. They can offer features like code navigation and auto-complete, providing accurate suggestions.

The power of object-orientation

TypeScript supports Object-Oriented Programming (OOP) concepts such as classes, interfaces, inheritance, etc.

ECMAScript defines the standards and novelties of JavaScript

TypeScript takes great care to include all these new features with each update.

References:

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