Answer a Question
Sign In

Specify Generic Type

Wednesday, November 6, 2019

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

  • Do:

    specify generic types when possible

  • Avoid:

    the use of any for generics

  • Avoid:

    not specifying a generic type

  • Why:

    specifying generic types enables type safety

Avoid

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'));

Do

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'));
Brian Love
Brian is a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. He regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, Brian enjoys skiing, hiking, and being in the outdoors. Brian recently launched lookout.dev where you can find best practices and expert advice on topics ranging from TypeScript, Angular, React, Node.js and more.
Google Developers Expert

Whoa 🤚 You need to sign in to join the discussion.

Don't worry, if you start a comment, we'll save it for when you return. 😉