Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property 'key' does not exist on type 'string | { key: string; element: Element; }'

WHy is this error message

Property 'key' does not exist on type 'string | { key: string; element: Element; }'

when I input the following code

<th key={header?.key ? header.key : header} ref={ref}>

Header has the following type, so it should allow .key

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export type Column<T = any> = {
  header: {key: string, element: JSX.Element} | string;
  size: keyof typeof COLUMN_SIZES;
  sortable?: boolean;
  property: string;
  ref?: React.MutableRefObject<HTMLTableHeaderCellElement>;
  render?: (datum: T, index?: number) => string;
  renderer?: React.FC<IRendererProps>;
};

>Solution :

string doesn’t have a key property, and header can be a string, so TypeScript doesn’t allow you to access its key unconditionally. You need to add a check to narrow the type before accessing key.

One way to do that is to check whether it’s actually a string:

typeof header == 'string' ? header : header?.key
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading