Typescript: Extract inferred external Props from a React Component with defaultProps

Created on 28 Aug 2018  路  7Comments  路  Source: microsoft/TypeScript

Search Terms

ElementProps, ElementConfig, "component props with defaultProps"

Suggestion

Now that TypeScript infers the external Props API for a Component with defaultProps, it would be helpful to add a type that returns the inferred props from a component. Flow accomplishes this with "React.ElementConfig".

Use Cases

  • Extending React components and re-using their prop types without re-writing them.

Examples

class Test extends React.Component<{ foo: string, bar: number }> {
  static defaultProps = {
    foo: 'baz',
  }

  render() {
    ...
  }
}

type TestProps = React.ElementConfig<Test>; // { foo?: string, bar: number }

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. new expression-level syntax)
External

Most helpful comment

You are looking for:

type TestProps = JSX.LibraryManagedAttributes<typeof Test, Test["props"]>;

which is what the TypeScript compiler is in fact using.

All 7 comments

You are looking for:

type TestProps = JSX.LibraryManagedAttributes<typeof Test, Test["props"]>;

which is what the TypeScript compiler is in fact using.

Would be nice to put that in the React .d.ts file for consistency

It also would be nice if TypeScript would automatically detect the type of defaultProps

class Test extends React.Component<{ foo: string, bar: number }> {
  static defaultProps = {
    bar: 'baz', <-- Error, Type 'string' is not assignable to type 'number'.
  }

  render() {
    ...
  }
}

So we don't have to declare defaultProps as Partial<{ foo: string, bar: number }> or something like that.

(Sorry, if this should be an issue on its own I will gladly create it)

@cheeZery I don't understand the example. You have declared that the bar prop is a number but are setting a default that is a string?

Yeah, exactly, and that's the bug I would like TypeScript to detect :-) Sorry, that I didn't made that clear! At the moment you can set whatever key value pairs you want in defaultProps. TypeScript should know that keys of the declared Props interface are allowed here. Or am I missing something why this shouldn't be the case?

@cheeZery Yes, please file a new issue as this is unrelated to the current issue.

Is there any plan to add JSX.LibraryManagedAttributes<typeof T, T["props"]> into d.ts for React?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Zlatkovsky picture Zlatkovsky  路  3Comments

uber5001 picture uber5001  路  3Comments

wmaurer picture wmaurer  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

dlaberge picture dlaberge  路  3Comments