0

Context

Guys, i'm starting with Typescript and right now i'm just struggling with some concepts.

When specifying a parameter to a function, for example, i set the type like that:

function example(test: string){...}

But right now i'm getting into states and i see types being specified like that:

type User = {
  id: string;
  name: string;
  avatar: string;
}

const [user, setUser] = useState<User>();

Question

So my question is: What's the difference between : and <> ?

  • One is a type annotation, the other is a generic type parameter. They have nothing in common aside from being used in the type system. – VLAZ Jun 23 '21 at 16:44
  • @VLAZ thanks for comming up with this new terms. Was able to do some research and now it makes sense! – Bruno Vercelli Jun 23 '21 at 16:51

1 Answers1

0
function example(test: string){...}

This sets the type of a function parameter. If you call this function, you have to call it with string as its first argument.


const [user, setUser] = useState<User>();

This is a generic type parameter. This is a way to pass a type to some other other type for it to use in ways specific to that type. It may set the type a function argument, or it may do something completely different. In this case, it's declaring the type of the state that useState will manage. It sets the type of the default value (the argument you pass to useState(), the and the type returned value (user will be of type User, and setUser() will only accept a User as a value to set).

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337