Specify Generic Type
Wednesday, November 6, 2019
Specify Generic Type
Specify generic types when TypeScript declarations support generics. Generics enable library and application developers to create reusable type definitions that can implement a a variety of scenarios, all while enforcing type safety.
Type safety is important when developing software with TypeScript, and without generics developers would be forced to either create highly redundant declarations or to revert to using the any
type. When using a library that supports TypeScript generics you should specify the generic when possible.
Instructions
specify generic types when possible
the use of any
for generics
not specifying a generic type
specifying generic types enables type safety
Code Examples
Specify generics when extending the Component class
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
/** The application props. */
interface AppProps { }
/** The application state. */
interface AppState {
name: string;
}
/** Define application component specifying the props and state generics. */
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
/** Set state. */
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
render(<App />, document.getElementById('root'));
Omitting generics
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
/** Define application component without specifying the props and state generics. */
class App extends Component {
constructor(props) {
super(props);
/** Set state. */
this.state = {
named: 'React'
};
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
</div>
);
}
}
/** Error: Property 'name' does not exist on type 'Readonly<{}>' **/
render(<App />, document.getElementById('root'));
Have a question or comment?