Last active
April 25, 2018 21:24
-
-
Save guilhermepontes/18efba5520959687154f853797ea97f4 to your computer and use it in GitHub Desktop.
Use generics to set the state in React | Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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