reactjs - How to enforce key when creating an element? - Stack Overflow

admin2025-04-18  3

I want to make sure a key is always passed when instantiating React components. The use case is that I have an array that is filled with components conditionally. For some reason, TypeScript is not happy with my type definition though.

Argument of type 'Element' is not assignable to parameter of type 'WithKey'.
  Type 'ReactElement<any, any>' is not assignable to type '{ key: Key; }'.
    Types of property 'key' are incompatible.
      Type 'string | null' is not assignable to type 'Key'.
        Type 'null' is not assignable to type 'Key'.
declare const user: { role: string; id: string };
import * as React from 'react';
import { Route } from 'react-router';

type WithKey = React.ReactElement & { key: React.Key }

export const App = () => {
  const routes: WithKey[] = [];

  if (user.role === 'admin') {
    // should not error
    routes.push(<Route key='1' path='/dashboarrd' />);
  }

  if (user.role === 'employee') {
    // should error
    routes.push(<Route path='/profile' />);
  }
}

Here is a playground as well.

I want to make sure a key is always passed when instantiating React components. The use case is that I have an array that is filled with components conditionally. For some reason, TypeScript is not happy with my type definition though.

Argument of type 'Element' is not assignable to parameter of type 'WithKey'.
  Type 'ReactElement<any, any>' is not assignable to type '{ key: Key; }'.
    Types of property 'key' are incompatible.
      Type 'string | null' is not assignable to type 'Key'.
        Type 'null' is not assignable to type 'Key'.
declare const user: { role: string; id: string };
import * as React from 'react';
import { Route } from 'react-router';

type WithKey = React.ReactElement & { key: React.Key }

export const App = () => {
  const routes: WithKey[] = [];

  if (user.role === 'admin') {
    // should not error
    routes.push(<Route key='1' path='/dashboarrd' />);
  }

  if (user.role === 'employee') {
    // should error
    routes.push(<Route path='/profile' />);
  }
}

Here is a playground as well.

Share edited Jan 30 at 7:26 DarkBee 15.5k8 gold badges72 silver badges118 bronze badges asked Jan 30 at 7:04 tdranvtdranv 1,34018 silver badges48 bronze badges 1
  • 1 TIL you can use imports in the TS playground
转载请注明原文地址:http://anycun.com/QandA/1744933673a89685.html