Typescript: React 16.3 getDerivedStateFromProps support

Created on 17 Apr 2018  路  4Comments  路  Source: microsoft/TypeScript

In our application we use generics quite extensively for instance take the code:

export class Form<T> extends React.Component<IFormProps<T>, State> {

    componentWillReceiveProps(newProps: IFormProps<T>) {
        // snip
      }

}

In React 16.3 they are looking to change the API to:

export class Form<T> extends React.Component<IFormProps<T>, State> {

    static getDerivedStateFromProps(nextProps: IFormProps<T>, prevState: State) {

    }

This is pretty breaking as we can't reference the class generic from the static. I don't know the technical reason why they are forcing us to use statics beyond perhaps performance? I honestly see this is more of a react issue and having them not use static but I can see them just saying its a Typescript issue.

Are there any plans to support this generics in this way or any workarounds?

Most helpful comment

oops sorry I misread your issue.

You should be able to do this :

export class Form<T> extends React.Component<IFormProps<T>, State> {

    static getDerivedStateFromProps<U>(nextProps: IFormProps<U>, prevState: State) {

    }

But since you are not supposed to call getDerivedStateFromProps directly, you could use any instead

export class Form<T> extends React.Component<IFormProps<T>, State> {

    static getDerivedStateFromProps(nextProps: IFormProps<any>, prevState: State) {

    }

All 4 comments

Type definitions are hosted on DefinitelyTyped.

16.3 new lifecycle events have been merged already

See this PR

This isn't about the typings (I have the above) its about loss of support of generics:

image

This is probably less of an issue than I thought so I'll close for now. It would be nice to share any restrictions on the class generic mind you.

oops sorry I misread your issue.

You should be able to do this :

export class Form<T> extends React.Component<IFormProps<T>, State> {

    static getDerivedStateFromProps<U>(nextProps: IFormProps<U>, prevState: State) {

    }

But since you are not supposed to call getDerivedStateFromProps directly, you could use any instead

export class Form<T> extends React.Component<IFormProps<T>, State> {

    static getDerivedStateFromProps(nextProps: IFormProps<any>, prevState: State) {

    }
Was this page helpful?
0 / 5 - 0 ratings