3

I've upgraded to typescript 3.2.2 and this code which used to compile is now not compiling:

export const Heading: React.SFC<HeadingProps> = ({ level, className, tabIndex, children, ...rest }) => {
  const Tag = `h${level}`;

  return (
    <Tag className={cs(className)} {...rest} tabIndex={tabIndex}>
      {children}
    </Tag>
  );
};

With the error:

Property 'tabIndex' does not exist on type 'IntrinsicAttributes'.

3 Answers 3

6

This is a little late and tested on TypeScript 3.4:

Replace

const Tag = `h${level}`;

with

const Tag = `h${level}` as "h1" | "h2" | "h3" | "h4" | "h5" | "h6";

I'm still not sure about tabIndex, but now TypeScript can infer other properties like children.

Sign up to request clarification or add additional context in comments.

Comments

2

This is a little verbose, but I've been able to get everything to cleanly compile with full typing by doing it this way:

const H = (
  props: React.DetailedHTMLProps<
    React.HTMLAttributes<HTMLHeadingElement>,
    HTMLHeadingElement
  >
): JSX.Element => React.createElement("h" + this.props.size, props);

Then you can use <H> in your component and use the size property to dictate with heading tag to use.

Comments

0

I don't use React.SFC. I have used the React component just like:

export default class Heading extends React.Component<Props, {}>

maybe you will use the below code, I think you will find the solution:

interface HeadingProps {
    tabIndex: any,
}

    export const Heading: React.SFC<HeadingProps> = ({ level, className, tabIndex, children, ...rest }) => {
      const Tag = `h${level}`;

      return (
        <Tag className={cs(className)} {...rest} tabIndex={tabIndex}>
          {children}
        </Tag>`enter code here`
      );
    };

and also need to define the tabIndex in level class.

my code:

import Level from './component/level';
interface HeadingProps {
    className: string,
    tabIndex: any,
}

export default class Heading extends React.Component<HeadingProps, {}>{
render(){
 const {className, tabIndex}
 return (
        <Level className={cs(className)} {...this.props.rest} tabIndex= 
          {tabIndex}>
          {this.props.children}
        </Level>
      );
    };
}


interface Props {
    tabIndex: any,
}

export default class Level extends React.Component<Props, {}> {
render(){
   return (
            <h1 tabIndex={tabIndex}>
              {this.props.text}
            </h1>
        )
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.