最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - What does <T> in javascript for? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited May 1, 2019 at 1:54 CertainPerformance 371k55 gold badges350 silver badges356 bronze badges asked May 1, 2019 at 1:30 Weijing Jay LinWeijing Jay Lin 3,2387 gold badges39 silver badges57 bronze badges 8
  • 2 This is likely not Javascript code, but Typescript code. Is this a .ts file? This sounds like Typescript generics. typescriptlang/docs/handbook/generics.html – Nate Commented May 1, 2019 at 1:32
  • 1 No, it is .js file github./facebook/react/blob/master/packages/react/src/… – Weijing Jay Lin Commented May 1, 2019 at 1:41
  • 2 Given we're talking about the react source, I'd wager it's flow: flow/en/docs/types/generics – HPierce Commented May 1, 2019 at 1:41
  • 1 It's flow ;) github./facebook/react/blob/master/packages/react/src/… – HPierce Commented May 1, 2019 at 1:42
  • 2 If I had any amount of confidence in what that syntax was trying acplish, 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 Commented May 1, 2019 at 1:48
 |  Show 3 more ments

1 Answer 1

Reset to default 6

It's a generic flow type annotation. It gets added to the code to be able to spot type missmatches using the IDE. During pile 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
发布评论

评论列表(0)

  1. 暂无评论