What is the best way to define a Typescript type that can be either a string or an HTML element

I’m struggling to figure out how to set a Typescript type that can be either a string or an HTML element. It seems like it should be simple, but I can’t find the answer anywhere.

Basically, I want to be able to pass a string or HTML as the "title" prop.

<Dialog
     title={<div>some HTML</div>}
   </Dialog>

   <Dialog
      title={"Some string"}
   </Dialog>

   export type DialogProps = {
     title?: Element | string | undefined;
   };

Answer №1

If you are looking for the type React.ReactNode, it encompasses JSX.Element as well as string, number, and undefined, among others.

The relevant block of the type definitions is shown below:

type ReactText = string | number;
type ReactChild = ReactElement | ReactText;
interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

Ambiguity with Element

If you simply use the type Element without any prefix, it will use the definition from lib.dom.ts. The JSX namespace in React has its own definition for JSX.Element.

In your example, the element <div>some HTML</div> is a JSX.Element, which cannot be assigned to the Element type.

function requiresElement(el: Element) {}

requiresElement(<div>some HTML</div>); // error

Argument of type 'JSX.Element' is not assignable to parameter of type 'Element'.

Type 'Element' is missing the following properties from type 'Element': attributes, classList, className, clientHeight, and 123 more.

Typescript Playground Link

Answer №2

To define your props type, consider using an interface:

interface PopUpProps {
   title: JSX.Element | string
}

interface State {}

class PopUp extends React.Component<PopUpProps, State> {
  ...
}

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 causes an undefined error to occur when setting default values after destructuring and assigning props in JavaScript?

Encountering issues with TypeScript in React that have arisen after updating Typescript, ESLint, Prettier, React, and Webstorm to their latest versions. Interestingly, no errors occur when the code is run on the web despite these updates. An example of a ...

Extending an interface in TypeScript to include an Array

Can I implement a parent interface in Angular 4? export interface Devices extends Array<Device> { } The error 'Class 'DevicesModel' incorrectly implements interface 'Devices'. Property 'includes' is missing in typ ...

Out of nowhere, encountering TS2322 Typescript errors, causing type mismatches during the compilation phase

I am facing an issue with AWS Codebuild while deploying APIs written in lambda and exposed via API Gateway using Koa. The build process is throwing an error related to type assignment. src/components/chart-color-settings/chart-color-settings.ts(11,13): err ...

Error: "Cannot find module 'tsc' in TypeScript, Express, and React application during deployment on Heroku

Currently, I am working on developing an Express app using TypeScript and a React app bootstrapped with create-react-app in JavaScript. The project has a specific directory structure which can be viewed here. The server code is located within the server/sr ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

Steps to ensure that the autocomplete is reset to its default settings every time the page is

I am experiencing an issue with the accountInfo property where the targetValue does not reset to default as expected. I have tried using useEffect to solve this problem, but it's not working. Any suggestions on how I can achieve this? Whenever the ac ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

build a key-value pair collection in Angular 2

Struggling to figure out how to create an associative array in Angular2? I've attempted the following: onSubmit(){ let inputfield:any[] = []; for(var i=0; i<this.inspectionform.value["inputfileds"].length; i++){ if(this.inspectionform.valu ...

Required file missing in React application unable to locate

I have a project organized in the following way: - my-app - src - some files - public - index.html - ... When I run npm start, the application functions as expected. Now, I am looking to rename src to application! After renami ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Error: __importDefault is throwing a ReferenceError and is not found

I recently started learning Angular and ran into a problem while working on my index.component.ts file. There seems to be an error: Uncaught ReferenceError: __importDefault is not defined Attached is a screenshot of the error for reference ...

Tips for eliminating unnecessary module js calls in Angular 9

https://i.sstatic.net/3R7sr.png Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module J ...

Encounter an Unexpected Token Issue when using NextJS-auth0 in Jest

I am facing a problem with my Next.js app that is integrated with the nextjs-auth0 package. Whenever I attempt to test a particular file and include the following import: import { getSession } from '@auth0/nextjs-auth0'; An error occurs, stating ...

The Nuxt Vuex authentication store seems to be having trouble updating my getters

Despite the store containing the data, my getters are not updating reactively. Take a look at my code below: function initialAuthState (): AuthState { return { token: undefined, currentUser: undefined, refreshToken: undefined } } export c ...

Issue with Angular 6 where data is not binding to the UI on initialization

I am struggling with binding dynamic data to the UI and Data tables on my website. Despite trying various methods, I have not been able to achieve success. Currently, I am using the smart admin latest theme for development. When I make a call to the API, ...

I am interested in utilizing the request-reply pattern with KafkaJS in a TypeScript environment. Could you provide guidance on how to successfully implement this?

I am new to Kafka and I am trying to implement the request-reply pattern using kafkajs in TypeScript. However, my current implementation is very basic and the consumers inside producers are taking too long to start, causing delays. Is there a better way to ...

Error: Cannot access property 'tb' of an undefined value

While running the Application, I encountered an error in the declaration of constants.ts file where I was assigning data from a json file to constant variables. In the json file named object.json, I had some data structured like this: { "furniture": { ...