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.