H
H
hamster1410952021-10-17 06:23:49
typescript
hamster141095, 2021-10-17 06:23:49

How to describe types in a given React component?

I create a Typography component - which in prop's accepts its variant (h2,h1, p, etc.), but I cannot describe the types for the returned component, it says that string - Property 'children' does not exist on type 'IntrinsicAttributes'.
P/s Where = any = I can't describe the type there

import React from 'react';
import classNames from 'classnames';
import { TypographyType, TypographyTypeStyle } from './types/types';

import './typographyStyle.scss';

interface ITypography {
  variant: TypographyTypeStyle;
  children: React.ReactChild;
}

const Typography: React.FC<ITypography> = ({ variant, children, ...props }) => {
  const Component: any= TypographyType[variant];
  return (
    <Component
      className={classNames({
        typography: true,
        [`typography__variant_${variant}`]: variant,
      })}
      {...props}
    >
      {children}
    </Component>
  );
};

export default Typography;


Variant typing
export enum TypographyTypeStyle {
  h1 = 'h1',
  h2 = 'h2',
  h3 = 'h3',
  h4 = 'h4',
  p1 = 'p1',
  p2 = 'p2',
}

export const TypographyType = {
  [TypographyTypeStyle.h1]: 'h1',
  [TypographyTypeStyle.h2]: 'h2',
  [TypographyTypeStyle.h3]: 'h3',
  [TypographyTypeStyle.h4]: 'h4',
  [TypographyTypeStyle.p1]: 'p',
  [TypographyTypeStyle.p2]: 'p',
};


Usage
<Typography variant={TypographyTypeStyle.h4}>Text 4</Typography>


I also tried React.ReactChild, writes that string does not apply to React.Child, and when I manually write to types, there are no problems
const Typography: React.FC<ITypography> = ({ variant, children, ...props }) => {
  const Component= 'h1';
  return (
    <Component
      className={classNames({
        typography: true,
        [`typography__variant_${variant}`]: variant,
      })}
      {...props}
    >
      {children}
    </Component>
  );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-10-17
@hamster141095

Try to fix like this:

export const TypographyType = {
  [TypographyTypeStyle.h1]: 'h1',
  [TypographyTypeStyle.h2]: 'h2',
  [TypographyTypeStyle.h3]: 'h3',
  [TypographyTypeStyle.h4]: 'h4',
  [TypographyTypeStyle.p1]: 'p',
  [TypographyTypeStyle.p2]: 'p',
} as const;

as const will fix literal types on the object, although the object itself will make it readonly, if this does not suit you, then you can write as const opposite each field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question