I'm trying to pass keys
as a React prop:
import * as React from "react";
import { render } from "react-dom";
const keys: string[] = ["a", "b"];
function App({keys}: string[]) {
return (
<div>
{keys.map((key: string) => (
<li>{key}</li>
))}
</div>
);
}
const rootElement = document.getElementById("root");
render(<App keys={keys} />, rootElement);
However, I get these errors:
Property 'map' does not exist on type '() => IterableIterator'.
Type 'string[]' is not assignable to type '() => IterableIterator'.
Why is this, and how to fix it?
CodePudding user response:
You're typing your whole props as string[]
instead of just keys
. Embed keys
prop in an object:
function App({ keys }: { keys: string[]; }) {
// ...
Or using an interface:
interface AppProps {
keys: string[];
}
function App({ keys }: AppProps) {
// ...
Or a type:
type AppProps {
keys: string[];
}
function App({ keys }: AppProps) {
// ...
To go further: Differences Between Type Aliases and Interfaces