Ways to resolve the error "TS2741: The property 'children' is not present"

Encountering an issue with one of my custom elements:

https://i.sstatic.net/4EDnZ.png

Error TS2741: Type '{ }' is missing property 'children' required in type 'StringChildren'

The component in question is Comment

export function Comment({children}: StringChildren)
export type FlatString =  string | Iterable<string>
export interface StringChildren { children: FlatString }

After clicking "Add missing attributes," the corrected code becomes:

<Comment children={''}>
    Hello &lt; secret comment
    Multi-line {'-->'}
</Comment>

This solution resolves the error that was triggered.

It appears that TypeScript is not recognizing the content as equivalent to the children prop. The reason for this discrepancy is unclear.

My configuration file, tsconfig.json, includes:

{
    // Compiler options specified here
}

Note that React is not being used in this project.


A similar error can be found on TS Playground, although not identical: TS Playground

The 'children' prop of this JSX tag expects type 'string | string[]', implying multiple children, yet only a single child was provided (Error 2745)

How does 'string | string[]' necessitate multiple children when using just 'string'? This should indicate a single child.

In the compiled output,

const test = _jsx(Comment, { children: "hello" });

We observe that

<Comment>hello</Comment>
successfully creates a 'children' prop as a string. So why is the error occurring?


Changing the TS version to 4.9.5 results in the same error message mentioned earlier:

Property 'children' is missing in type '{}' but required in type 'StringChildren' (Error 2741)

Answer №1

To ensure proper functionality, make sure to incorporate the JSX.ElementChildrenAttribute. By simply including the following snippet of code:

declare namespace JSX {
    interface ElementChildrenAttribute {
        children: unknown  // specify children name to use
    }
}

This instructs TypeScript that the contents of the element should be treated as the children prop. The specific type provided in the code above may not be crucial; what truly matters is setting up this association.

You can find more details on this topic at: https://www.typescriptlang.org/docs/handbook/jsx.html#children-type-checking

If TypeScript does not automatically detect your JSX typings, remember to manually include it in your tsconfig file, like so:

{
    "include": [
        "node_modules/@mpen/jsxhtml/jsx.d.ts"
    ]
}

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

A versatile generic type infused with dynamic typing and optional parameter flexibility

Looking to develop a function that can accept an optional errorCallback parameter. In cases where the consumer of this function does not provide a callback, I aim to default to a preset handler. The key criteria here are strong typing and utilizing the ret ...

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

connect validation of the form to a separate component from the current one

Currently, I am working on creating a searchable-dropdown component that I intend to use in multiple components. However, I am facing an issue with binding form validation to this component. For instance, I have a form for creating a user and I need to bi ...

Error TS2393 in Typescript: Multiple function declarations found within a Node/Express application

In my TypeScript node + express application, I have implemented a function in some API routes that looks like this: function cleanReqBody(req) { req.body.createdBy = req.user; req.body.modifiedBy = req.user; req.body.modified = new Date(); } Howeve ...

Injectable error occurred while injecting one @Injectable() into another

I'm encountering an issue with Angular2 Dependency Injection. When attempting to inject one class into another, I am receiving the following error: Error Message: "Cannot resolve all parameters for 'ProductService'(undefined). Make sure tha ...

Utilizing a Single Class with TypeScript in Angular and Node.js Servers: Best Practices

I've named the file containing the following code as models.ts import {BusStage} from "./busStage"; export class BusRoute { name: string; origin_direction_1: string; origin_direction_2: string; stops: number; id: string; meta ...

The ValidationPipe does not function properly when utilizing app.useGlobalPipes

Hello! I'm looking to implement the ValidationPipe globally using useGlobalPipes. Currently, my code looks like this: import 'dotenv/config'; import {NestFactory} from '@nestjs/core'; import {ValidationPipe} from '@nestjs/com ...

"An error in the signature index results in the failure of the

I'm encountering a coding issue that's puzzling me. The TypeScript index signature I included in my code is as follows: const ships: { [index: string]: Ship } = {}; This snippet of code contains the problematic line: recieveAttack(e: any) { ...

What is the best method to include spacing between strings in an array and then combine them into a csv-friendly format?

The method I am currently employing involves the following: var authorsNameList = authors.map(x => x.FirstName + ' ' + x.LastName); Yet, this generates an outcome similar to this: Bob Smith,Bill Jones,Nancy Smith Nevertheless, the desired ...

Angular Tutorial: Understanding the Difference Between TypeScript's Colon and Equal To

I've been diving into the Angular4 tutorial examples to learn more about it. https://angular.io/docs/ts/latest/tutorial/toh-pt1.html One of the code snippets from the tutorial is as follows: import { Component } from '@angular/core'; @Co ...

Using capital letters with interpolated language keys

The issue: I'm currently facing a problem with i18next. It allows variable interpolation in strings, like "AddNew": "Add new {{item}}". However, I have a language where the grammar requires "{{item}}" to be the first word, as in "AddNew": "{{item}} t ...

Vue: Defining typed props interface including optional properties

I created a method that I want to be accessible on all my Vue instances, so I can use it in case of an error and display a specific error component. Similar to the functionality provided by vue-error-page. Since I am working with typescript, I now want to ...

Ways to develop a dynamic Promise-returning Function

I find myself in a situation where I am aware of the type of data that will be returned when making a request to an API. Here is the function I have: const fetchData = async (url: string, options?: Object): Promise<any> => { const res = await f ...

Achieve a new version without relying on conditions

I am looking to achieve the same functionality as the code below but without using any condition statements. HelloFunction(x){ If(x<0){ Console.log("greater"); }Else{ Console.log("smaller"); } }; HelloFun ...

declare wrong TypeScript type in external library

I am currently using winston 3.0 in combination with the @types/winston types. Unfortunately, it seems that these types are not completely compatible, leading to an error in the types that I am unsure how to rectify. Below is the code snippet in question: ...

Combining multiple arrays in angular 11: A step-by-step guide

I am facing an issue with two arrays received from a URL in Angular. I am attempting to combine the two arrays into a single array. "admin":[ { "Name":"John", "Age":34 }, { "Name:"Joe", "Age":56 } ], "users":[ { "Name":"John", "Age":34 }, { "Name:"Joe", ...

What is the best way to determine a comprehensive map of every sub-store, their functions, and what data they contain?

Summary: Can all actions with their payloads be automatically grouped by sub-store in a composite store using a single type entity (e.g., interface)? I have implemented a Redux store with multiple sub-stores structured as follows: There is an action setA ...

Leverage Angular's filtering capabilities with a variety of input options

I am in need of help with a filter for my simple list of people, where each person has a name and a first name. I want to be able to search for a specific field or both fields at the same time. https://i.sstatic.net/pPRjO.png The HTML code is as follows: ...

Differences between Typescript compilation: Using dot notation vs square brackets when accessing non-existent properties

Imagine having the given class and code snippet: class myClass{ x: number; } const obj = new myClass(); obj.y = 7; // produces a compile error. Property 'y' does not exist on type myClass. obj['y'] = 7; // compiles without any issu ...

Can Vue instances support private computed properties?

Vue is a versatile tool that I utilize for both service classes and components. When it comes to reactive computeds, they prove to be incredibly beneficial. However, I often find myself wanting a clear way to differentiate between public interface compute ...