0

I'm new in Typescript. In the following code, I see using generic with "&". I don't understand what's that means? I think 2 interfaces can join and like 1 interface work?

import * as React from 'react';

export interface StatefulCounterWithDefaultProps {
 label: string;
 initialCount?: number;
}

interface DefaultProps {
 readonly initialCount: number;
}

interface State {
  readonly count: number;
}

export const StatefulCounterWithDefault: 
React.ComponentClass<StatefulCounterWithDefaultProps> =
class extends React.Component<StatefulCounterWithDefaultProps & 
 DefaultProps> {

static defaultProps: DefaultProps = {
  initialCount: 0,
};

readonly state: State = {
  count: this.props.initialCount,
};

componentWillReceiveProps({ initialCount }: StatefulCounterWithDefaultProps) {
  if (initialCount != null && initialCount !== this.props.initialCount) {
    this.setState({ count: initialCount });
  }
}

handleIncrement = () => {
  this.setState({ count: this.state.count + 1 });
}

render() {
  const { handleIncrement } = this;
  const { label } = this.props;
  const { count } = this.state;

  return (
    <div>
      <span>{label}: {count} </span>
      <button type="button" onClick={handleIncrement}>
        {`Increment`}
      </button>
    </div>
  );
}
};

In this code : React.Component<StatefulCounterWithDefaultProps & DefaultProps> 2 interfaces join together with &. How does it work?

Saeed Jalali
  • 416
  • 4
  • 16
  • 4
    That's called type intersection. http://www.typescriptlang.org/docs/handbook/advanced-types.html – Roberto Zvjerković Oct 03 '18 at 08:02
  • 2
    Possible duplicate of [What does the ampersand (&) mean in a TypeScript type definition?](https://stackoverflow.com/questions/38317625/what-does-the-ampersand-mean-in-a-typescript-type-definition) – Aleksey L. Oct 03 '18 at 08:11

1 Answers1

0

Those are called intersection types. See https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types

Juan M. Medina
  • 618
  • 1
  • 5
  • 13