最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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 Improve this question edited Jan 30 at 7:26 DarkBee 15.6k8 gold badges72 silver badges117 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
发布评论

评论列表(0)

  1. 暂无评论