Custom objects do not return true for Symbol.hasInstance

The TypeScript playground encounters an issue with the Symbol.hasInstance built-in symbol, while it functions properly for other symbols.

Testing other symbol methods such as Symbol.match and Symbol.replace show no problems, but Symbol.hasInstance is not returning the expected result despite being identified correctly in console.log messages.

I have tried running the code on both the TypeScript playground and MDN, but they both return false with the generated code.

If you wish to try this code yourself, simply paste it into the TypeScript playground at https://www.typescriptlang.org/play/index.html

class Array1 {
    static [Symbol.hasInstance](instance) {
        console.log(instance);
        return Array.isArray(instance);
    }
}
console.log(Symbol.hasInstance.toString());
let arr: string[] = ['a', 'b'];
console.log(arr instanceof Array1);
console.log([] instanceof Array1);
// expected output: true
// current output is false

Upon clicking "run," the generated code fails to return true on the left-hand side.

var Array1 = /** @class */ (function () {
     function Array1() {
    }
    Array1[Symbol.hasInstance] = function (instance) {
        console.log(instance);
        return Array.isArray(instance);
    };
    return Array1;
}());
console.log(Symbol.hasInstance.toString());
var arr = ['a', 'b'];
console.log(arr instanceof Array1);
console.log([] instanceof Array1);

It should be returning true instead of false.

Answer №1

The official playground restricts changing too many compiler options, mainly targeting ES5 which does not support Symbol.hasInstance introduced in ES2015 and later versions. Using ES2015 as the target will produce functional code. Experiment with it here.

However, is there a way to generate functional code while still targeting ES5? It may seem unnecessary since Symbol.hasInstance won't work on unsupported engines, but here's some TypeScript that will produce functioning JavaScript even in the official playground set for ES5:

class Array1 { }
Object.defineProperty(Array1, Symbol.hasInstance, {
    get: () => (instance) => {
        console.log(instance);
        return Array.isArray(instance);
    }
});
console.log(Symbol.hasInstance.toString());
let arr: string[] = ['a', 'b'];
console.log(arr instanceof Array1);

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

What is the best way to merge two array files together using jq?

Imagine having file one: [1, 1, 2] then file two: [2, 3, 3] Is there a way to combine these arrays from the two files without altering their content? I'm looking for an output like this: [1, 1, 2, 2, 3, 3] On a side note, I am interested in concate ...

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

What is the reason for needing to specify event.target as an HTMLInputElement?

I am currently working on a codebase that uses Material Ui with theme overrides. As I set up my SettingContext and SettingsProvider, I find myself facing some syntax that is still unclear to me. Let's take a look at the following code snippet: const ...

How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be ["Name", "Account", "Status"] ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Union does not contain the specified property in Typescript

Here are the types that I have: Foo { foobar: any } Bar { fooBarBar: any; } I want to use a function defined like this: this.api.submit(param: Foo | Bar) When trying to use it, I encountered an issue: this.api.submit(param.foobar) // does no ...

Issue with setting value using setState in TypeScript - what's the problem?

Every time I attempt to update the value of currentRole, it appears highlighted in red. Here is a screenshot for reference: const Container: React.FC<ContainerProps> = ({ children }) => { const [role, setRole] = useState<string>(); useE ...

What is the recommended way to use the async pipe to consume a single Observable property in a view from an Angular2

Suppose I have a component with the following property: import { Component, OnInit } from 'angular2/core'; import { CarService } from 'someservice'; @Component({ selector: 'car-detail', templateUrl: './app/cars/ ...

Exploring ways to compare and update values in an array of objects using JavaScript

I have a situation where I need to compare the names and values of two arrays filled with objects. const array1 = [ { name: 'Sarah', value: null }, { name: 'Michael', value: null } ] const array2 = [ { na ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

Generating Pulumi Outputs for exporting as an external configuration file

I am currently utilizing Cloudrun in GCP and am interested in summarizing the created APIs with API Gateway. To achieve this, a Swagger/OpenAPI v2 document needs to be generated containing the google-generated URLs for the Cloudrun Services. How can I ext ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

What is the best method for adding a JSON array with objects to an already existing table?

After incorporating Bootstrap into my HTML file, I designed a basic table. To populate this table with data from an external JSON file upon clicking a button, I utilized XMLHttpRequest and JSON.parse successfully. However, I encountered difficulties when t ...

Error in declaring type even after including .d.ts file

I have encountered a situation where the npm package update-immutable does not come with a built-in typescript definition or a definition in @types. To resolve this issue, I created a type definition file within my project. As a result, VS Code is now able ...

"Implement a function to append a new item to all JSON objects in an array if they share a common value with a different JSON object in the array using

Hi there, I'm new to Vue Js and I'm currently working on adding or merging new items in all JSON objects within an array that share the same value with another JSON object. I know how to push a new JSON object into an existing one, but I would re ...

Finding the sub-array within the main array that is shifted one position to the right

I have a large numpy array called a=[55,12,12....] . My goal is to create sub-arrays of size 300 starting from index 55 in the array a, then shift one position to the right from index 12 to obtain a new sub-array. This process needs to be repeated until th ...

Detecting when users stop scrolling in Angular 5

Is there a way to toggle visibility of a div based on user scrolling behavior? I'd like the div to hide when the user scrolls and reappear once they stop. I've attempted to achieve this effect using @HostListener, but it only seems to trigger wh ...

Transforming date and timezone offset into an isoDate format using moment.js

When retrieving data from the API, I encounter Date, Time, and Offset values in separate columns. My goal is to obtain an ISO date while maintaining the original date and time values. const date = "2019-04-15" const time = "13:45" const ...

TS2322 error: Attempting to assign type 'any' to type 'never' is invalid

Currently, I am utilizing "typescript"- "3.8.3", and "mongoose": "5.9.11". Previously, my code was functional with version "typescript": "3.4.x", and "mongoose": "4.x". Here is a snippet of my code: https://i.stack.imgur.com/j3Ko2.png The definition for ...