What is it about Kyle Simpson's OLOO methodology that seems to swim against the tide of Typescript's popularity?

Disclaimer: this post might come across as impulsive. Warning for Typescript beginners! Also, a bit of a vent session.

Recently, I delved into the OLOO approach from the YDKJS book series within a Typescript and Node environment.

// ideal JS syntax

let Account = {
  get id(){
    return this._id;
  },
  get name(){
    return this._name;
  },
  init(id, name){
    this._id = id;
    this._name = name;
  }
}

let TypedAccount = {
  identify(){
    console.log(`This is ${this.name}'s ${this._type} account`);
  },
  init_L2(type){  
    this._type = type;
  }
}
Object.setPrototypeOf(TypedAccount, Account);

function createAccount(id, name, type){
  let instance = Object.create(TypedAccount);
  instance.init(id, name);
  instance.init_L2(type);
  return instance;
}

let o1 = createAccount(101, 'Tom', 'Savings'),
o2 = createAccount(102, 'Jerry', 'Current');
console.log (o1.identify());
console.log (o2.identify());

The primary appeal of OLOO was its simplicity. However, due to the Typescript compiler, I find myself writing more code than necessary; something I wouldn't have to do with the class-based approach.

  1. I have to define an interface like IAccount for each type like Account, in order to ensure client usages can be checked for/auto-completed. Although, I sometimes resort to using the any escape when needed.
  2. TS complains about using undeclared fields, so I need to specify all the fields and their types before accessing them with this.field. It's not too much effort but still adds complexity. For example, _id : defaultValue;
  3. When dealing with object literals that include a map [strings => numbers], I use a nested object. But TS requires me to provide the type for both key and value. This leads to creating an interface to annotate the field.

interface IMapStringsToNumbers {
   [ key: string ]: number;
}

// 
let Account = {
   _holdings : <IMapStringsToNumbers> {}

Perhaps the last two points are not directly related to OLOO. Is there a simpler solution?

Answer №1

Creating a class Account in TypeScript results in the simultaneous creation of two entities:

  • An entity named Account which represents the type of instances of the Account class during compilation
  • A run-time entity (variable) named Account which represents the class itself (similar to a constructor in Javascript)

All the necessary connections are established, making it clear that new Account returns an object of the Account type.

However, if you use let Account = ..., you only create a variable without any automatic type tracking by TypeScript. It won't recognize relationships between Account and TypedAccount based on prototype assignments.

Subjectively speaking, implementing this "simple" pattern may require adding lines like:

init_L2(type){  // avoid collision with base#init

or

Object.setPrototypeOf(TypedAccount, Account)

In conclusion: Avoid these complexities. Stick with classes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with blueprintjs/core type in JupyterLab Extension after running npm install

Developed a JLab extension and saved it to Git repository. Established a new environment and successfully pulled the code, which was also verified by a friend. Subsequently, included a new react object to the extension and pushed it back to Git in a fresh ...

A More Straightforward Approach to Unsubscribing from Observables in Angular 7

Is there a way to simplify the process of automatically unsubscribing from Observables when a component is destroyed using takeUntil? It becomes tedious having to repeat the same code in multiple components. I am looking for a solution that allows me to a ...

Leveraging Prototype's Class creation function to declare confidential and safeguarded attributes and functions

Looking for a solid approach to defining private and protected properties and methods in Javascript? Check out this helpful discussion here on the site. Unfortunately, the current version of Prototype (1.6.0) doesn't offer a built-in method through it ...

When two $scopes are updated simultaneously, it leads to the duplication of data

Here is the snippet of code I am working with: $scope.addToOrder = function(index) { var tempItem = $scope.item; if (tempItem[index].validate == true){ if (_.isEmpty($scope.item2) == true) { $scope.item2.push ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

Tips for concealing the ID value within a URL or parameter

I just started learning Angular JS and I have a question about hiding parameters in the URL when clicking on anchor tags to send data to another controller. I don't want any ID or its value to be visible in the URL. Is it possible to hide parameters i ...

Breaking down a string and then retrieving elements from an array

Just diving into the world of Javascript and jQuery, so I have a simple query. I've got a date that I need to break down into a string and then display it as an array. var date = "12/10/2010"; var dateArray = date.split(/); $('#printbox') ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

Using scripted <svg> with <defs> and attempting to reference it via JavaScript results in failure

My goal is to dynamically generate svg path elements in html using JavaScript. I would like to place these paths within a <defs> element so that they can be reused later in <use> xlink:href elements. However, after creating the paths (by pr ...

Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the fiel ...

Ways to display the modal once the user initiates the action

Is there a way to delay loading my modal HTML codes until after the user clicks a button, rather than having them load automatically with the template? HTML <!-- Template Codes--> <button data-toggle="modal" data-target="#modal-content" type="bu ...

Using jQuery to handle multiple AJAX XML requests

Currently, I am working on developing a JavaScript XML parser using jQuery. The idea is that the parser will receive an XML file containing information along with multiple links to other XML files. As the parser runs, it will identify tags within the file ...

What is the best way to customize the interval time for my specific situation?

I'm working on setting an interval in my app and I have the following code: HTML <div class="text"> {{currentItem.name}} </div> <ul> <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li> ...

Problem encountered while trying to import npm module in React Native

Working on developing an android app and currently in the process of importing the spotify-web-api-node module. In my index.android.js file, I have added the following line: import SpotifyWebApi from 'spotify-web-api-node'; However, when I try ...

The jQuery onClick function functions effectively for the initial two clicks; however, it ceases to

I am currently experimenting with jQuery to dynamically load a specific div from another page on my server into a designated section on the existing page. While the code is successfully functioning for the first two clicks on the website, it fails to work ...

When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user cred ...

Creating a JavaScript file to incorporate into an HTML document

I stumbled upon this code snippet here This code allows me to fetch data from a php file and insert it into a div using jQuery. While the tutorial works perfectly, I'm planning to use this for about 9-10 different links and thought of consolidating a ...

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

What are the best scenarios for creating a constructor in Angular 2 using Typescript?

Check out these sample constructors I found in the Angular 2 documentation: export class AppComponent implements OnInit { title = 'Tour of heroes'; heroes: Hero[]; selectedHero: Hero; constructor(private heroService: HeroService ...

Combining strings with objects in Javascript: A step-by-step guide

In the code snippet provided, I am combining variables to create a path to another existing object and its attribute. The issue is that I always receive a string, but I would like to somehow convert it into an object. // SET CUSTOM CONTENT FOR COLUMN IF ...