Skip to content

Instantly share code, notes, and snippets.

@guilhermepontes
Last active April 25, 2018 21:24
Show Gist options
  • Save guilhermepontes/18efba5520959687154f853797ea97f4 to your computer and use it in GitHub Desktop.
Save guilhermepontes/18efba5520959687154f853797ea97f4 to your computer and use it in GitHub Desktop.
Use generics to set the state in React | Typescript
import React from 'react';
interface State = {
name: string;
age: number;
alive: boolean;
}
class App extends PureComponent<{}, State> {
public state = {
name: 'Bill'
age: 22,
alive: true,
}
private update = (property: string, value<T>: T): void => this.setState({
[property]: value,
});
public componentDidMount() {
this.update('name', 'Paul');
this.update('alive', true);
this.update('age', 23);
}
public render() {
const { name, age, isDead } = this.state;
return `${name}, ${age}, ${isDead}`;
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment