TypeScript

Sentiment Analysis Using TypeScript Without Dependencies

Sentiment analysis is usually a task that requires a specialised dataset and machine-learning techniques to implement properly. However, I thought it might be a nice exercise to try and implement sentiment analysis with TypeScript without training models. // Define a type for the sentiment result type Sentiment = 'positive' | 'neutral' | 'negative'; // Class to perform sentiment analysis on a given text class SentimentAnalysis { // Arrays of positive and negative words to use in the analysis private positiveWords = ["love", "like", "great", "good", "happy", "awesome"]; private negativeWords = ["hate", "dislike", "bad", "angry", "sad", "terrible"]; // Method to perform sentiment analysis on a given text public getSentiment(text: string): { sentiment: Sentiment, positiveWords: number, negativeWords: number, neutralWords: number } { // Convert the text to lowercase to make the analysis case-insensitive const lowerText = text.toLowerCase(); // Sum up the number of times each positive word appears in the text let positiveScore = this.positiveWords.reduce((acc, word) => { // Use a regular expression to match the word in the text return acc + (lowerText.match(new RegExp(word, 'g')) || []).length; }, 0); // Sum up the number of times each negative word appears in the text let negativeScore = this.negativeWords.reduce((acc, word) => { // Use a regular expression to match the word in the text return acc + (lowerText.match(new RegExp(word, 'g')) || []).length; }, 0); // Calculate the number of neutral words by subtracting the positive and negative words from the total number of words let neutralScore = lowerText.split(' ').length - positiveScore - negativeScore; // Compare the number of positive and negative words and return the sentiment result if (positiveScore > negativeScore) { return { sentiment: "positive", positiveWords: positiveScore, negativeWords: negativeScore, neutralWords: neutralScore }; } else if (positiveScore < negativeScore) { return { sentiment: "negative", positiveWords: positiveScore, negativeWords: negativeScore, neutralWords: neutralScore }; } else { return { sentiment: "neutral", positiveWords: positiveScore, negativeWords: negativeScore, neutralWords: neutralScore }; } } } // Create an instance of the SentimentAnalysis class const sentimentAnalysis = new SentimentAnalysis(); // Analyze some sample text const result = sentimentAnalysis.getSentiment("I love this code and think it is great!"); // Log the result console.log(result); This code uses a class called SentimentAnalysis to perform sentiment analysis on a given text. The class has two arrays of positive and negative words and a method called getSentiment that performs the analysis.

How to Extend the Window Object in TypeScript

In many cases when you’re working with TypeScript, there are type definitions available for almost every package out there. However, in some circumstances, you might find yourself working with a third party that adds a property to the window object. Think a script tag like how Google Analytics works by adding in the ga property to the window. It doesn’t matter if you are using Angular, React, Vue, Svelte, Aurelia, or any other framework or library, this approach works for all TypeScript projects.

How to Add Typings to the Global TypeScript Window Object

Does this error look familiar? Property ‘AddressFinder’ does not exist on type ‘Window & typeof globalThis’.ts(2339) There will come a time in TypeScript when you are not dealing with package-managed dependencies from Npm. These will come in the form of scripts added into the head or footer of your application. Furthermore, these global scripts might not have typings. You will also run into this error for numerous jQuery plugins and other libraries which work on the premise of modifying the global Window object.

Getting Typescript 3.7 To Work With Webpack and ts-loader

At the time of writing this post, TypeScript 3.7 is in beta. Eventually, this post will become irrelevant. But, for the moment if you are trying to get TypeScript 3.7 Beta or any of the RC builds working with Webpack and ts-loader you might have encountered a bunch of red text in your console. In my case, I had target: "esnext" set in my tsconfig.json file which the ts-loader plugin should read and set the appropriate settings. And yet, TypeScript 3.7 Beta was not working despite making sure everything was up to date.

Mocking Default Imports In Jest With TypeScript

If you are writing tests using Jest and you use TypeScript, there is a good chance you have encountered an error along the lines of TypeError: defaultsDeep_1.default is not a function or TypeError: myClass.default is not a constructor when trying to test a file that is using a default import from a module. You most likely have read countless StackOverflow questions, but none of the solutions will solve the issue. You’ve read the Jest documentation (which is quite extensive), but still no mention of mocking default module imports with TypeScript.

Module ES2015 and TypeScript 2.4 Dynamic Imports

Introduced in TypeScript 2.4 is support for the ECMAScript dynamic imports feature. If you didn’t see the announcement or read it properly, you’re probably here because you’re getting the following error. In my case I use Webpack and I was trying to add in some dynamic import goodness and getting this error: Dynamic import cannot be used when targeting ECMAScript 2015 modules. You’re probably thinking, this is crazy considering dynamic imports are an ECMAScript feature, not a TypeScript one. The tell is in the error, if your module is set to es2015 you’re targeting ES6 and dynamic imports are a feature not due for release until ECMAScript 2018.

Configuring Git Pre Commit Hook And TSLint (automatically)

If you’re a TypeScript user and you’re reading this, then you’re using TSLint (most likely). Recently, a situation at work arose where even though TSLint warnings were being thrown in the editor as well as terminal output, some developers (tsk tsk) were still committing these warnings. Naturally, a pre-commit Git hook is the right candidate for this. Being able to run TSLint to ensure that before a developer can even commit let alone push, only valid code conforming to the tslint.json file can be pushed.

Dealing With Tslint Errors/Warnings In Third Party Files

This might be a bit of an edge case for some, but recently I needed to use a third-party script in my Aurelia TypeScript application that wasn’t installable through Npm. I could have carefully changed it to conform to my TSLint guidelines, but that would have been more effort than I wanted to spend. I just wanted to include the file in a vendor folder and then import it without worrying how it’s written, whether it uses single or double quotes or what indentation setting it uses.

Getting Visual Studio Code To Work With Next Versions of TypeScript

Recently whilst helping out a client with an Aurelia TypeScript project, I encountered a situation where the latest development version of TypeScript 2.0 was being used, but some of the newer features like filesGlob support were not being picked up. Module resolution and other things were also an issue. Turns out you can configure Visual Studio Code to use a local version of TypeScript through a setting directive inside of a project settings file.

String Enums In TypeScript

Sometimes you want to specify in your application multiple allowed values. For example, you might have a method which allows you to perform server requests and the only allowed values are; GET, POST, UPDATE, DELETE and PUT. Ideally you want to prevent any developer from calling a method with an invalid value. Normally you would use an enum for this, most languages support the use of an enum which might be used for this purpose.