Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning type to a React SFC function declaration in TypeScript

So, you can assign a type of React.FC<PropsType> to a variable so that it is understood as a React Stateless Functional Component like so:

//Interface declaration
interface ButtonProps {
  color: string,
  text: string,
  disabled?: boolean
}

// Function Component
let Button: React.FC<ButtonProps> = function(props){
  return <div> ... </div> ;
}

However, I am having trouble understanding how to assign the same type to a FC built as a function declaration:

//Props interface already declared
function Button(props){
  render <div> ... </div>;
}

I could assign the type to the props argument, and it would partly help since it would show what I expect to get from the caller (minus the children prop) but I don't think that would help with any intellisense from the calling context. I also have no idea what to set as the return type of the second example.

Thank you!

like image 757
Sammy I. Avatar asked Jul 09 '18 17:07

Sammy I.


1 Answers

Not sure if you've found the answer by now, but adding a static type to a named function is nearly identical to how you did it in your initial example

Based on your example:

//Props interface already declared
function Button(props): React.ReactElement<Props> {
  render <div> ... </div>;
}

// Or you could store the function in a named variable
const ButtonComponent: React.FunctionComponent<Props> = function Button(props): React.ReactElement<Props> {
  render <div> ... </div>;
}

// Using shorthand type
const ButtonComponent: React.FC<Props> = function Button(props) {
  render <div> ... </div>;
}

You can read up more on adding types to react components in this article

Note: Best practice is to use React.FC instead of React.SFC since it's now deprecated in recent versions of React

like image 189
Emma Avatar answered Nov 07 '22 18:11

Emma