Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

eg. a sample code from React source code

export function useState<S>(initialState: (() => S) | S) {
  const dispatcher = resolveDispatcher();
  return dispatcher.useState(initialState);

what does <s> here means?

This is likely not Javascript code, but Typescript code. Is this a .ts file? This sounds like Typescript generics. typescriptlang.org/docs/handbook/generics.html – Nate May 1, 2019 at 1:32 Given we're talking about the react source, I'd wager it's flow: flow.org/en/docs/types/generics – HPierce May 1, 2019 at 1:41 If I had any amount of confidence in what that syntax was trying accomplish, I'd write an answer. But unfortunately I'd just have to read the - maybe related - documentation for generics. Either way, I'd bet dollars to donuts that a transpiler (babel) is involved. I'm fairly sure that syntax isn't part of ECMAScript. – HPierce May 1, 2019 at 1:48

It's a generic flow type annotation. It gets added to the code to be able to spot type missmatches using the IDE. During compile time, these annotations get removed (as they are invalid JS).

This annotation basically means that you can useState with any type you want, and you could also pass an initializer function that returns a certain type:

  useState("test") // T is string
  useState(1) // T is number
  useState(() => 1) // T is number
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.