Jake
Jake

Reputation: 68

Passing context into a react SFC using Typescript

I'm trying to pass context into a SFC as outlined in the react docs, but typescript is freaking out about it. I've reproduced the issue on codesandbox.io, and inlined relevant info bellow. So-

How do I tell Typescript Chill, everything will be okay?

Error Message:

Property 'contextTypes' does not exist on type '(props: ShirtProps, context: any) => Element'.

A simplified version of my component looks like this:

import * as React from 'react';
import * as PropTypes from 'prop-types';
import { ShirtProps as Props } from '../types';

// tslint:disable-next-line:no-any
export const Shirt = (props: Props, context: any) => {
  return (
    <h1>Example text size is {props.scale}</h1>
  );
};

// Typescript throws the following warning:
// Property 'contextTypes' does not exist on type '(props: ShirtProps, context: any) => Element'.
Shirt.contextTypes = {
  parallaxController: PropTypes.object.isRequired
};

export default Shirt;

Thanks!

*Any other tips are welcome- I'm just getting started with Typescript AND React.

Upvotes: 3

Views: 1394

Answers (1)

WayneC
WayneC

Reputation: 5740

If you tell it that Shirt is an SFC it should compile (with the type React.SFC<Props>):

import * as React from 'react';
import * as PropTypes from 'prop-types';
import { ShirtProps as Props } from '../types';

// tslint:disable-next-line:no-any
export const Shirt: React.SFC<Props> = (props: Props, context: any) => {
  return (
    <h1>Example text size is {props.scale}</h1>
  );
};

Shirt.contextTypes = {
  parallaxController: PropTypes.object.isRequired
};

export default Shirt;

Upvotes: 3

Related Questions