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?
-
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
1 Answer
Reset to default 6It'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