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

6
  • What is that type supposed to mean? It makes no sense to use a function as a type. Commented Jun 27, 2019 at 11:10
  • How do you want to use Demo? Why do you want to limit its children to a specific type? Commented Jun 27, 2019 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. Commented Jun 28, 2019 at 2:20
  • @MuratKaragöz I want to limit the Demo component only accepting children of NameView component, not others like div or span. Commented Jun 28, 2019 at 2:24
  • possible duplicate of stackoverflow.com/questions/44475309/… Commented Jul 3, 2019 at 8:25

2 Answers 2

1
interface Props {
  children: (typeof NameView)[];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use typeof (function name) i.e typeof NameView

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.