React/Typescript - Confused about syntax

Viewed 45

I'm just starting out with Typescript/React and i'm trying to understand what this all means. I come from a C# background so this is a bit new to me. I've gone through a few tutorials but I'm still a little confused on the syntax of this.

For starters, what does this line even mean?...

type OnUserClick = (u: UserTat) => any

And this interface... the onClick function is defined as () => OnUserClick rather than OnUserClick... why is this?

interface IBProps {
  user: UserTat
  onClick: () => OnUserClick
}
2 Answers
type OnUserClick = (u: UserTat) => any

OnUserClick is a function that takes one parameter (named u in the type definition, but JS/TS doesn't have named parameters, so it could be called anything when used); that param is of type UserTat, and the function returns any, which means it could be any possible return type. Putting down an any is usually not a great idea, since any code that calls that function will have to cast the return value or do its own checking to figure out what got returned.

interface IBProps {
  user: UserTat
  onClick: () => OnUserClick
}

This interface means that anything implementing IBProps has two properties: a user, which is of type UserTat, and an onClick, which is a function that takes no arguments and returns something of type OnUserClick. An example (making up the definition of a UserTat) would be:

{
  user: { name: 'Zac Anger' ... }
  onClick: () => (u) => ({ clicked: 'true' })
}

Since OnUserClick itself is defined as a function that returns something, then that part of IBProps may be a bug; it's saying that IBProps.onClick is a function that returns a function that takes a UserTat and returns an any.

type OnUserClick = (u: UserTat) => any

Defines that OnUserClick is a function that accepts a parameter u which is from UserTat type and returns any type (any)

interface IBProps {
  user: UserTat
  onClick: () => OnUserClick
}

Defines an interface that includes:

  1. user from type UserTat
  2. onClick function from type OnUserClick that's declared above.
Related