首页 > 解决方案 > html 元素数组或字符串 typescript

问题描述

简而言之,我想拥有stingsHTMLInputElements作为我的类型。

  const tableHeaders = [
    <input type="checkbox" />,
    "Some String",
    "Another Some String",
  ];

零件

import React, { ReactChildren } from 'react';

interface TableProps {
  headers: (string | HTMLInputElement)[];
}

export const Table = ({ headers }: TableProps) => (
    <table>
      <thead>
        <tr>
          {headers.map((name: string) => (
            <th key={name}>{name}</th>
          ))}
        </tr>
      </thead>
    </table>
);

错误

Type '(string | Element)[]' is not assignable to type 'string[]'.
  Type 'string | Element' is not assignable to type 'string'.
    Type 'Element' is not assignable to type 'string'.  TS2322

    160 |       {!noResults && (
    161 |         <TableShell data-id="TableShell">
  > 162 |           <Table headers={tableHeaders}>
        |                  ^
    163 |             {state.map(
    164 |               ({
    165 |                 id,

期望的结果:

将任意标题作为任何 html 输入和/或字符串。

在此处输入图像描述

一个可能的解决方案?

import React, { ReactChildren } from 'react';

type headerType = ReactChildren | React.ReactNode | string;

interface TableProps {
  headers: headerType[];
}

export const Table = ({ headers }: TableProps) => (
    <table>
      <thead>
        <tr>
          {headers.map(
            (name: headerType, index) => (
              <th key={`${index}_tableHeader`}>{name}</th>
            )
          )}
        </tr>
      </thead>
    </table>
);

标签: javascripttypescript

解决方案


推荐阅读