Definitelytyped: [styled-components] Wrong props inference

Created on 30 Nov 2018  路  3Comments  路  Source: DefinitelyTyped/DefinitelyTyped

I have the following component:

interface ColProps extends HTMLAttributes<HTMLDivElement> {
  custom: number;
}

class Col extends React.Component<ColProps> {
  static propTypes: {
    custom: PropTypes.Validator<number>;
  };

  render() {
    return null;
  }
}

When I try to use it like this:

<StyledCol custom={24} />

Then TypeScript complains that custom does not exists:

Type '{ custom: number; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<{}, never> & Partial<Pick<{}, never>>, never> & { theme?: any; } & { as?: "symbol" | "object" | "input" | "progress" | "select" | "data" | ... 166 more ... | undefined; }'.
  Property 'custom' does not exist on type 'IntrinsicAttributes & Pick<Pick<{}, never> & Partial<Pick<{}, never>>, never> & { theme?: any; } & { as?: "symbol" | "object" | "input" | "progress" | "select" | "data" | ... 166 more ... | undefined; }'

To "solve" it, I need to remove extends HTMLAttributes<HTMLDivElement> from props interface.

Any idea what could be wrong? Types of styled-components looks horribly complicated to investigate the issue 馃檪

Background: I'm trying to style a Col component from https://github.com/ant-design/ant-design/blob/ca7d265b2b4395fc2c54ab0c719be12d1478a048/components/grid/col.tsx.

TypeScript: 3.2.1
@types/react: 16.7.9
@types/styled-components: 4.1.2
@types/prop-types: 15.5.6

@Kovensky @Igorbek @Igmat @Lavoaster

Most helpful comment

Try using React.ComponentPropsWithoutRef<'div'> instead of HTMLAttributes; I should just add @deprecated annotations to all those things. But I'm not sure that'll actually _fix_ your problem, just use the correct types.

As for the error, I think it might be a side effect of https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30730, check if your local @types/react isn't actually a ^16.7.9 that got updated to 16.7.10.

All 3 comments

Try using React.ComponentPropsWithoutRef<'div'> instead of HTMLAttributes; I should just add @deprecated annotations to all those things. But I'm not sure that'll actually _fix_ your problem, just use the correct types.

As for the error, I think it might be a side effect of https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30730, check if your local @types/react isn't actually a ^16.7.9 that got updated to 16.7.10.

@Kovensky
React.ComponentPropsWithoutRef<'div'> didn't help. Also, React types are exactly 16.7.9 as 16.7.10 was causing a lot more issues.

Interesting, the problem seems to go away if you remove the static propTypes.

This can happen if your component is not assignable to ComponentClass because your propTypes is incorrect.

https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30913 could help with that someday but it's not ready.

Was this page helpful?
0 / 5 - 0 ratings