Re:A guide to useEffect in React
by jameslk on Monday March 11, 2019 @02:41PM
(#19361593)
> With Hooks you almost never need to explicitly type the type of state of a component [...] While when using class-based Components, you'd have to specify the state type as a generic argument
You don't need to do this. You can accomplish the same thing with class syntax. Here's an example:
class MyComponent extends Component<Props> {
state = {
inferredNum: 1, // TS will infer this to be a number
explicitNullableString: null as string | null, // Tell TS this will be either null or a string
}
...
> And you'd have to use some kind of Partial<State> type when assigning only some values of the state in the property constructor.
I can't say I've ever run into this problem with TS and React but maybe I'm not understanding what you're saying? Do you have an example?
> Similar issues exist when using the static defaultProps field in TypeScript
Here's what I do:
defaultProps: Partial<Props> = {...}
That doesn't seem such a big deal?
> And if you ever tried to strictly type your HOCs or renderProps you know how hard it was, sometimes utilizing the conditional/mapped generic types feature of TS. This is completely gone with Hook.
It wasn't hard to me but I can understand why others don't like generics. Hooks have their own learning curve, so you're trading one thing for another.
> You'd have to override the non-null check using TS exclamation point operator.
You don't need to do this. You can accomplish the same thing with class syntax. Here's an example:
> And you'd have to use some kind of Partial<State> type when assigning only some values of the state in the property constructor.I can't say I've ever run into this problem with TS and React but maybe I'm not understanding what you're saying? Do you have an example?
> Similar issues exist when using the static defaultProps field in TypeScript
Here's what I do:
That doesn't seem such a big deal?> And if you ever tried to strictly type your HOCs or renderProps you know how hard it was, sometimes utilizing the conditional/mapped generic types feature of TS. This is completely gone with Hook.
It wasn't hard to me but I can understand why others don't like generics. Hooks have their own learning curve, so you're trading one thing for another.
> You'd have to override the non-null check using TS exclamation point operator.
This has been fixed with TS 3 I believe.