Reactjs 为什么在使用泛型的特定设置中,在可选字段中将类型设置为未知?

Reactjs 为什么在使用泛型的特定设置中,在可选字段中将类型设置为未知?,reactjs,typescript,Reactjs,Typescript,我试图修复一些关于碳组分反应数据表的类型,但在使一个属性可选方面遇到了困难。我创建了自己的演示来展示这个问题: import React from "react"; interface Human { name: string; age: number; address?: string; } interface ButtonProps<R extends Human> { name: R["name"]; age: R["age"]; address?:

我试图修复一些关于碳组分反应数据表的类型,但在使一个属性可选方面遇到了困难。我创建了自己的演示来展示这个问题:

import React from "react";

interface Human {
  name: string;
  age: number;
  address?: string;
}

interface ButtonProps<R extends Human> {
  name: R["name"];
  age: R["age"];
  address?: R["address"];
  onClick?: Function;
}

interface RenderProps<R extends Human> {
  human: R;
  getButtonProps(data?: ButtonProps<R>): ButtonProps<R>;
}

export interface DataTableProps<R extends Human> {
  rows: R[];
  render(props: RenderProps<R>): React.ReactNode;
}

class DataTable<R extends Human> extends React.Component<DataTableProps<R>> {
  render() {
    return this.props.rows.map((h) => {
      const buttonProps: () => Human = () => ({ ...h }); // This is only to be able to see the type of buttonProps in IDE

      return this.props.render({ human: h, getButtonProps: buttonProps });
    });
  }
}

interface TableButtonProps {
  name: string;
  address?: string;
}

const TableButton = (props: TableButtonProps) => (
  <button>Button for {props.name}</button>
);

export const Demo = () => {
  // This works
  const man1: Human = {
    name: "Anna",
    age: 30,
  };

  // This seems to be ok since "address" is optional
  // but this isn't working!
  const man2 = {
    name: "Tom",
    age: 32,
  };

  // This works
  const man3 = {
    name: "John",
    age: 40,
    address: "404 Street Unknown",
  };

  return (
    <DataTable
      rows={[man2]}
      render={({ getButtonProps }) => {
        return <TableButton {...getButtonProps()} />;
      }}
    ></DataTable>
  );
};
由于某种原因,
address
属性具有
unknown
类型。当我使用像
man1
man3
这样的语法时,一切正常,您可以在
rows=
处替换它。为什么
man2
即使类型仍设置为“扩展人”也不工作?打字稿丢失了吗

您可以使用
npx create react app mydemo--template=typescript

//编辑:

interface ButtonProps<R extends Human> {
  name: Human["name"];
  age: Human["age"];
  address?: Human["address"];
  onClick?: Function;
}
界面按钮操作{
姓名:人类[“姓名”];
年龄:人类[“年龄”];
地址?:人类[“地址”];
onClick?:函数;
}
似乎也在解决此问题并“保护”地址类型

interface ButtonProps<R extends Human> {
  name: Human["name"];
  age: Human["age"];
  address?: Human["address"];
  onClick?: Function;
}