这两种定义React.FunctionalComponent中props 的方式有什么显著的区别吗?

interface Props {
    username: string,
    age: number
}

const UserPanel: React.FunctionComponent = (props: Props) => (
    <div>{props.username}</div>
);

const UserPanel: React.FunctionComponent<Props> = (props) => (
    <div>{props.age}</div>
);

推荐答案

是的,有一个非常显著的区别:第一种 Select 是丢弃类型信息.

右侧的函数包括有关props 的信息,但随后您将其赋给一个没有该信息的变量.UserPanel‘S类型使用默认props {},因此任何使用用户面板的人都不能传递任何props .try 传递用户名props 或年龄props 将引发错误.例如:

const UserPanel: React.FunctionComponent = (props: Props) => (
    <div>{props.username}</div>
);

const SomeOtherCmponent = () => {
  // Error: Type '{ username: string; age: number; }' is not assignable to type 'IntrinsicAttributes'.
  return <UserPanel username="foo" age={100}/>
}

Playground link

您需要 Select 第二个选项:

const UserPanel: React.FunctionComponent<Props> = (props) => (
    <div>{props.age}</div>
);

或者你需要这样做:

const UserPanel = (props: Props) => (
    <div>{props.age}</div>
);

Typescript相关问答推荐

如果我有对象的Typescript类型,如何使用其值的类型?

带有微前端的动态React路由问题

属性的类型,该属性是类的键,其值是所需类型

与字符串文字模板的结果类型匹配的打字脚本

无法绑定ngModel.条件ngSwitchCase中的错误

隐式键入脚本键映射使用

在嵌套属性中使用Required

如何表示多层深度的泛型类型数组?

使用Dockerfile运行Vite React应用程序时访问env变量

有没有一种方法可以确保类型的成员实际存在于TypeScript中的对象中?

Typescript 类型守卫一个类泛型?

如何过滤文字中的类对象联合类型?

有没有办法防止类型交集绕过联合类型限制?

基于泛型的条件接口键

打字:注解`是字符串`而不是`布尔`?

导航链接不触发自定义挂钩

通过函数传递确切的类型,但验证额外的字段

Typescript泛型验证指定了keyof的所有键

定义一个只允许来自另一个类型的特定字符串文字的类型的最佳方式

基于泛型类型的条件类型,具有条目属性判断