0

In React.js, I've got a Function Component, and when I use the function name as type, get an error.

code sample:

import * as React from "react";
import { render } from "react-dom";

interface NameViewProps {
  name: string;
}
function NameView({ name }: NameViewProps) {
  return <div>{name}</div>;
}

interface Props {
  // ts error: Cannot find name 'NameView'.ts(2304)
  children: NameView[];
}

class Demo extends React.Component<Props> {
  render() {
    return (
      <div>
        <h2>in demo component with children div array</h2>
        {this.props.children}
      </div>
    );
  }
}

How can I use a function component’s name as a type?

You can try the codesandbox here

Jess
  • 620
  • 1
  • 7
  • 18
  • What is that type supposed to mean? It makes no sense to use a function as a type. – Murat Karagöz Jun 27 '19 at 11:10
  • How do you want to use ```Demo```? Why do you want to limit its children to a specific type? – AsukaSong Jun 27 '19 at 12:46
  • @AsukaSong I think it’s better to provide a specific type for `children` if we can. So we can prevent users of our component from passing the wrong children. – Jess Jun 28 '19 at 02:20
  • @MuratKaragöz I want to limit the `Demo` component only accepting children of `NameView` component, not others like `div` or `span`. – Jess Jun 28 '19 at 02:24
  • possible duplicate of https://stackoverflow.com/questions/44475309/how-do-i-restrict-the-type-of-react-children-in-typescript-using-the-newly-adde – AsukaSong Jul 03 '19 at 08:25
  • Does this answer your question? [How do I restrict the type of React Children in TypeScript, using the newly added support in TypeScript 2.3?](https://stackoverflow.com/questions/44475309/how-do-i-restrict-the-type-of-react-children-in-typescript-using-the-newly-adde) – Henry Woody Jan 04 '22 at 18:20

2 Answers2

1
interface Props {
  children: (typeof NameView)[];
}
Tolotra Raharison
  • 3,034
  • 1
  • 10
  • 15
0

Use typeof (function name) i.e typeof NameView