00

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

not specifying a generic type

Why

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

I am a software engineer and Google Developer Expert in Web Technologies and Angular with a passion for learning, writing, speaking, teaching and mentoring. I regularly speaks at conferences and meetups around the country, and co-authored "Why Angular for the Enterprise" for O'Reilly. When not coding, I enjoy skiing, hiking, and being in the outdoors. I started lookout.dev to break down the barriers of learning in public. Learning in public fosters growth - for ourselves and others.

Google Developers Expert

Discussions are healthy ❤️