Is it necessary to alert when there is a collision between a TypeScript type and a constant with the same name in a

    

I am encountering an issue with my TypeScript code. Here is a snippet from Project.ts:

   
import type { SomeType } from '../../types/Project';
// import { SomeType } from '../../types/Project'; tried this too

const SomeType = ({ s }: { s: SomeType }): JSX.Element => {
  return <>${s}</>;
};
   

Additionally, in the same file, I have:

   
export type SomeType = JSX.Element;
   

Even though I thought types and variables could coexist with the same name, the TS linter does not show any warnings but throws an error:

   

Identifier 'SomeType' has already been declared.

   

This has left me puzzled. Any ideas why this might be happening?

   

You can view this example on CodeSandbox: https://codesandbox.io/s/objective-glade-y94j58?file=/src/App.tsx

  

Answer №1

Although the solution provided by @Joel is a potential answer, I believe it does not fully address the question when simply stating "No".

To find more insights, you can refer to the solutions available here

Your query has an affirmative answer: YES, it is possible to use a type and variable with the same name in TypeScript as the typing will be eliminated during compilation (unlike variables).

The specific ESLint Rule that you are searching for is detailed here: no-shadow

// .eslintrc.js
module.exports = {
  "rules": {
    ...<your_other_rules>,
    // Make sure to disable the base rule to avoid incorrect errors being reported
    "no-shadow": "off",
    "@typescript-eslint/no-shadow": ["off", { ignoreTypeValueShadow: true, ignoreFunctionTypeParameterNameValueShadow: true }]
  }
};

Answer №2

Short and sweet, nah

Even if it's defined as a type, SomeType must have an available identifier (meaning a name not already utilized in the current context).

If altering the name of either the type or variable is not an option, you can create an alias for it.

import type { SomeType as AnotherNameForSameType } from '../../types/Project';

const SomeType = ({ s }: { s: AnotherNameForSameType }): JSX.Element => {
  return <>${s}</>;
};

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

Fade or animate the opacity in jQuery to change the display type to something other than block

I am currently using display: table and display: table-cell to vertically align multiple divs. However, I have encountered an issue when animating the opacity with jQuery using either fadeTo() or fadeIn. The problem is that it always adds inline style di ...

What is the best way to create a function that can identify and change URLs within a JSON file?

I'm currently working on a function that will replace all URLs in a JSON with buttons that redirect to another function. The modified JSON, complete with the new buttons, will then be displayed on my website. In my component.ts file, the section wher ...

Leveraging Javascript within MVC3, either on a master page or child page

I'm currently developing a web application utilizing MVC3 and I am curious about the best practices for incorporating JavaScript. Specifically, I am uncertain about whether to include JavaScript in the master page as well as in individual child pages. ...

I am currently struggling with a Typescript issue that I have consulted with several individuals about. While many have found a solution by upgrading their version, unfortunately, it

Error message located in D:/.../../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts TypeScript error in D:/.../.../node_modules/@reduxjs/toolkit/dist/configureStore.d.ts(1,13): Expecting '=', TS1005 1 | import type { Reducer, ReducersMapO ...

Can Puppeteer extract the complete HTML content of a webpage, including any shadow roots?

When using Puppeteer to navigate a webpage, I typically can retrieve the full HTML content as text with this code: let htmlContent = await page.evaluate( () => document.querySelector('body').innerHTML ); However, I am currently faced with ...

Best practices for effectively dismantling a Paper.js Scope

In my web project, I am utilizing multiple Paper.js canvases by creating a new scope for each of them. Due to the AJAX-driven nature of the site, I need to get rid of unnecessary instances when switching between subpages. Unfortunately, there is no built-i ...

JSReports encountered an unexpected token "<" in the JSON at position 0

Seeking assistance from those knowledgeable in JSReports, but open to suggestions from all... I've investigated the common issue of "unexpected token < in JSON at position 0", which typically arises when attempting to parse an HTML-formatted strin ...

PHP returns the result of form submission to JavaScript, allowing for distinction between successful and unsuccessful outcomes

JavaScript: $("#register-form").submit(function(event) { event.preventDefault(); $.post("./register.php", { username: $("#username").val(), password: $("#password").val(), passwordtwo: $("#passwordtwo").val(), email: $ ...

The Angular $http.post() successfully communicates with the server, however, it does not trigger any alerts within

Currently facing an issue with my angular code. I am using $http.post to send data to a php file that then saves the information into a database. Below is my controller: app.controller('send_data', function($scope, $http) { $http.defaults.he ...

Encountering surprising results while verifying a session token with parse.com

I am currently working on a project that involves using parse.com as my user manager. My goal is to create a login call to parse.com from the client side and then send the user's session token to my node.js server (which I will store as a cookie). On ...

Leveraging JQuery to Invoke Partial View

I have a partial view in my /Shared folder that is defined as follows: <div id="myProducts"> @Html.Partial("_ProductsList",Model) </div> I am attempting to refresh the _ProductsList view using jQuery. Specifically, I wan ...

Converting a string to a Date using TypeScript

Is it possible to convert the string 20200408 to a Date using TypeScript? If so, what is the process for doing so? ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

What is the best way to change CSS style for a button when clicked using JavaScript?

Is there a way to switch the background style of a CSS div when clicking the same button? function changeBg() { var divElem = document.getElementById("change-bg"); if (divElem.style.backgroundColor === "yellow") { divElem.style.backgroundColor ...

The output is generated by React useContext with a delay

When using the data obtained from useContext to verify if the logged-in user is an Admin, there seems to be a delay where it initially returns "undefined" and then after about 5 seconds, it provides the actual value. This causes the code to break since it ...

Evaluating function declaration - comparing interface to type alias

Here is a function that I need to create a validator for: function (n: number) { return {s: n}; } I have come across two options for creating the validator: Option 1: Interface interface ValidatorFnInterface { (n: number): { [key: strin ...

Print out two forms separately using HTML5

I'm currently tackling a project that condenses all content onto one convenient page, housing two forms. Despite my efforts, I have yet to find a successful solution. My goal is to print the Sales person form first, followed by the Customers section. ...

Creating dynamic types in TypeScript through existing types

Consider the following object: class Product { constructor( public metadata: Metadata, public topic: Topic, public title = 'empty' ) {} ... } I am looking to define an interface: interface State<T> { } This interface s ...

How to conceal certain columns in Angular Material when in mobile view

I am currently utilizing an Angular Material table: <div class="table-container"> <table mat-table [dataSource]="dataSource" class="child"> <mat-divider></mat-divider> <ng-container matColumnDef="title" ...

Error 400: Token Obtain Pair request failed in Django REST with simpleJWT and Vue 3 composition API

I'm encountering an issue with obtaining the refresh and access tokens when sending a form from my Vue app to the Django REST API. CORS has been enabled, and signing up through the REST API page or using Postman doesn't pose any problems. However ...