1601603874
An introduction to the utilization of Generics in TypeScript with examples grounded in real-world use cases, such as collections, approaches to error handling, the Repository Pattern, and so on. This article hopes to provide an intuitive understanding of the notion of software abstraction through Generics.
In this article, we’ll be learning the concept of Generics in TypeScript and examining how Generics can be used to write modular, decoupled, and reusable code. Along the way, we’ll briefly discuss how they fit into better testing patterns, approaches to error handling, and domain/data-access separation.
I want to enter into the world of Generics not by explaining what they are, but rather by providing an intuitive example for why they are useful. Suppose you’ve been tasked with building a feature-rich dynamic list. You could call it an array, an ArrayList
, a List
, a std::vector
, or whatever, depending upon your language background. Perhaps this data structure must have in-built or swappable buffer systems as well (like a circular buffer insertion option). It will be a wrapper around the normal JavaScript array so that we can work with our structure instead of plain arrays.
The immediate issue you’ll come across is that of constraints imposed by the type system. You can’t, at this point, accept any type you want into a function or method in a nice clean way (we’ll revisit this statement later).
The only obvious solution is to replicate our data structure for all different types:
const intList = IntegerList.create();
intList.add(4);
const stringList = StringList.create();
stringList.add('hello');
const userList = UserList.create();
userList.add(new User('Jamie'));
The _.create()_
syntax here might look arbitrary, and indeed, _new SomethingList()_
would be more straight-forward, but you’ll see why we use this static factory method later. Internally, the _create_
method calls the constructor.
This is terrible. We have a lot of logic within this collection structure, and we’re blatantly duplicating it to support different use cases, completely breaking the DRY Principle in the process. When we decide to change our implementation, we’ll have to manually propagate/reflect those changes across all structures and types we support, including user-defined types, as in the latter example above. Suppose the collection structure itself was 100 lines long — it would be a nightmare to maintain multiple different implementations where the only difference between them is types.
An immediate solution that might come to mind, especially if you have an OOP mindset, is to consider a root “supertype” if you will. In C#, for example, there consists a type by the name of object
, and object
is an alias for the System.Object
class. In C#’s type system, all types, be they predefined or user-defined and be they reference types or value types, inherit either directly or indirectly from System.Object
. This means that any value can be assigned to a variable of type object
(without getting into stack/heap and boxing/unboxing semantics).
In this case, our issue appears solved. We can just use a type like any
and that will allow us to store anything we want within our collection without having to duplicate the structure, and indeed, that’s very true:
const intList = AnyList.create();
intList.add(4);
const stringList = AnyList.create();
stringList.add('hello');
const userList = AnyList.create();
userList.add(new User('Jamie'));
Let’s look at the actual implementation of our list using any
:
class AnyList {
private values: any[] = [];
private constructor (values: any[]) {
this.values = values;
// Some more construction work.
}
public add(value: any): void {
this.values.push(value);
}
public where(predicate: (value: any) => boolean): AnyList {
return AnyList.from(this.values.filter(predicate));
}
public select(selector: (value: any) => any): AnyList {
return AnyList.from(this.values.map(selector));
}
public toArray(): any[] {
return this.values;
}
public static from(values: any[]): AnyList {
// Perhaps we perform some logic here.
// ...
return new AnyList(values);
}
public static create(values?: any[]): AnyList {
return new AnyList(values ?? []);
}
// Other collection functions.
// ...
}
#typescript #javascript #web-development #programming #developer
1624479720
Java is a type-safe programming language. Type safety ensures a layer of validity and robustness in a programming language. It is a key part of Java’s security to ensure that operations done on an object are only performed if the type of the object supports it.
Type safety dramatically reduces the number of programming errors that might occur during runtime, involving all kinds of errors linked to type mismatches. Instead, these types of errors are caught during compile-time which is much better than catching errors during runtime, allowing developers to have less unexpected and unplanned trips to the good old debugger.
Type safety is also interchangeably called strong typing.
Java Generics is a solution designed to reinforce the type safety that Java was designed to have. Generics allow types to be parameterized onto methods and classes and introduces a new layer of abstraction for formal parameters. This will be explained in detail later on.
There are many advantages of using generics in Java. Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.
This guide will demonstrate the declaration, implementation, use-cases, and benefits of generics in Java.
#java #guide to understanding generics in java #generics #generics in java #guide to understanding generics in java
1654588030
TypeScript Deep Dive
I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹
If you are here to read the book online get started.
Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.
You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.
All the amazing contributors 🌹
Share URL: https://basarat.gitbook.io/typescript/
Author: Basarat
Source Code: https://github.com/basarat/typescript-book/
License: View license
1630984612
In this video tutorial, Santiago will show how to use Typescript Generics to build Generic React Components. Do you find yourself duplicating your code to do the same things multiple times?
When building frontend applications, you may need to represent different entries in similar instances, for example aggregating search results within a single list. Separate typescript components are best to achieve this, but it can create problems such as code duplication which can slow down the process. Typescript generics provide an efficient solution to this problem by creating generic components.
⏱ TIMESTAMPS
0:00 - Intro
0:46 - Code Example
1:22 - Component Breakdown
3:58 - Using the Component
✔️ Santiago's code: https://codesandbox.io/s/typescript-generic-components-2zrus?file=/src/SelectList.tsx
#typescript #generics #react
1630958820
In this lesson we look at the key reason #generic type annotations are critical to maintainable type safe data structure creation in JavaScript / TypeScript
1623382800
In order to fully harness the power of TypeScript, you need to take advantage of all the tools it provides for developing reusable, type-safe code. In “Creating and Using Generics in TypeScript”, you will learn how to do more with less code. You will learn what generics are, how to recognize and use built-in generic types, and how to create your own generic functions, interfaces, and classes. When you are finished with this course, you will have a foundational understanding of TypeScript generics as well as the skills to begin using generics to build sophisticated web applications.
Subscribe: https://www.youtube.com/channel/UCmzhBmJCV6okfm8Sx-zElrg/featured
#typescript