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

Time:11-24

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

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>;
};

CodePudding user response:

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
  • Related