Is it advisable to prevent Set and Map from having unspecified generics in TypeScript?

Upon reviewing some old code that I wrote, I realized that I had neglected to specify a generic type for a Set. The type was set as Set<unknown>. Strangely, despite this, I found that I could still utilize all the methods of the Set without encountering any errors. This stands in contrast to untyped arrays, which would result in errors. For example:

const set = new Set();
set.has(1);

const map = new Map();
map.has(1);

const arr = []; // Variable 'arr' implicitly has type 'any[]' in some locations where its type cannot be determined.
arr.includes(1); // Variable 'arr' implicitly has an 'any[]' type.

I am now wondering how I can modify the behavior of Set and Map to also throw errors when their types are unknown.

Answer №1

In TypeScript, one way to restrict calling new Map() and new Set() without arguments is by merging your own declarations to produce unusable values like Map<never, never> and Set<never>:

// declare global { // if in module scope

interface SetConstructor {
  new(): Set<never>
}

interface MapConstructor {
  new(): Map<never, never>;
}

// } // if in module scope

The never type in TypeScript signifies that no valid value can be assigned. This will result in errors if you attempt to use such Maps and Sets:

const map = new Map();
map.has(1); // error!
// ---> ~
// Argument of type 'number' is not assignable to parameter of type 'never'.

const set = new Set();
set.has(1); // error! 
// ---> ~
// Argument of type 'number' is not assignable to parameter of type 'never'.

Check out this Playground link for the code

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

Ways to extract information from a database using a parameter

I am currently working with angular cli version 8.1.0 and I have a requirement to pass parameters in the URL and retrieve data from a PHP MySQL database. On the PHP side, everything is functioning correctly and the URL looks like this: http://localhost/rep ...

The $route object in Vue is not configured

Currently, I am delving into the realm of Vue router and aiming to achieve programmatic navigation without relying on <router-link> in my templates file. Here is a glimpse of my router and view setup: router = new VueRouter({ routes: [ ...

Tips for creating a TypeScript function that is based on another function, but with certain template parameters fixed

How can I easily modify a function's template parameter in TypeScript? const selectFromObj = <T, S>(obj: T, selector: (obj: T) => S): S => selector(obj) // some function from external library type SpecificType = {a: string, b: number} co ...

establish a compacted directory shortcut within alfresco

Although I'm not highly skilled in Javascript, I am in need of creating a webscript for Alfresco that can generate an alias [A] for a folder (space) [B]. If the structure of [B] appears as companyhome/site/special/my/fo/ld/de/r, [A] should be struct ...

Unable to invoke function on HTML element

Recently, I've ventured into writing jQuery-like functions in Vanilla JS. While my selectors seem to be working fine, I encounter an "is not a function" error when trying to call the append function on an HTML element. var $ = function(){ this.se ...

Navigating to a Different Vue or Page with Vue Form Wizard

I'm currently exploring VUE JS and trying to figure out how to redirect to another vue or page after submitting a form. I've been working with the sample code provided at https://stackblitz.com/edit/vue3-form-wizard-demo?file=src%2FApp.vue. Whil ...

Creating a Comprehensive Page Design with Bootstrap and the Latest Version of Vue

My goal is to develop a Single Page Application using Vue3 and the Bootstrap 5 framework with a simple layout of Header -> Content -> Footer. I want the Content section to fill the space between the header and footer, ensuring there is no overlap. Ho ...

Add() function is not duplicating the formatting

I'm attempting to replicate the content below inside a DIV. <ul class="pie-legend"><li><span style="background-color:#0066CC"></span>10-0-1</li><li><span style="background-color:#33CC33&q ...

Leveraging the power of nodejs functions within static HTML files in expressJs

Being a beginner in Javascript and Nodejs, I am uncertain about the best way to organize my project. I am currently working on creating a web interface for a C++ application using Nodejs and V8 to wrap a C++ API. My question is, can I utilize Express to se ...

What is the correct method for asynchronously loading CSS files in web development?

On a mission to enhance my website's performance, I set out to achieve the perfect score on PageSpeed Insights. Everything was going smoothly until I encountered an issue with CSS delivery. I initially achieved a flawless result by utilizing the prel ...

Create an HTML container surrounding the content within the parent tags

I'm looking to create a wrapper that acts as the immediate parent of any HTML markup added within a shared class. This will eliminate the need to manually add multiple wrapper divs and allow for the customization of layouts and backgrounds. Essential ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

Obtain the dimensions of the outermost layer in a JSON file

Could you please help me extract the dimensions (600*600) of the outermost layer from the JSON below dynamically? { "path" : "shape\/", "info" : { "author" : "" }, "name" : "shape", "layers" : [ { ...

The file size exceeds the server's upload limit, despite making changes to the php.ini file

I've encountered a problem trying to upload an .OBJ file to the server, resulting in an 'Error 1' message. The uploaded file surpasses the upload_max_filesize directive specified in php.ini This error is detailed on this page - http://ph ...

Can you explain to me the concept of "face indices" in Three.js and how it functions?

I am attempting to use Three.js to build a unique irregular polyhedron. In order to achieve this, I have decided to utilize the PolyhedronGeometry feature (refer to the documentation). However, I am encountering difficulty in understanding the concept of ...

JavaScript Calculator experiencing difficulty with adding two numbers together

I've been working on developing a calculator using HTML and JavaScript, but I'm facing an issue when trying to add two numbers together. Strangely enough, when attempting to calculate 1 + 0, I get the result of 512, and for 1 + 1, it returns 1024 ...

Struggling to understand the implementation of webpack's require.context() method

I'm currently working on an AngularJS project with webpack, and I'm looking for a way to import all the .js files in my project into webpack without manually adding each file path. Upon reviewing the webpack documentation, I came across the requi ...

Can the jQuery live function be triggered without the need for an event?

Using the live function in jQuery requires an event to trigger it. More information can be found in the official API documentation. $(".xyz").live('event', function(){ }); I am trying to make the above function run as soon as the dynamicall ...

Guide on how to retrieve Twitter Username and Profile Photo through the Twit NPM Package

Utilizing the twit npm package to retrieve the Authenticated Twitter Username and Profile Image, here is the code I am using: const Twit = require('twit'); let T = new Twit({ consumer_key: 'xxx', ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...