“?,typescript"/>

首页 > 解决方案 > "{text, comp} 的打字稿含义:NavProps & Comp“?

问题描述

我是打字稿的新手,遇到了一些类似下面的代码。

export interface Comp<T> {
  comp: (props: T) => JSX.Element;
}

export interface NavProps {
  text: string;
}

export default function Nav({text, comp}: NavProps & Comp<NavProps>) {
  let renderProps: NavProps = {
    text: text,
  };
  return comp(renderProps);
}

一些命名可能会令人困惑,但我不想弄乱工作代码。

这些代码打算做什么?特别是,这是什么?{text, comp}: NavProps & Comp<NavProps>

标签: typescript

解决方案


这段代码通常看起来像一个React组件。

{text, comp}: NavProps & Comp<NavProps>正在声明函数的参数,但使用解构

基本上

export default function Nav({text, comp}: NavProps & Comp<NavProps>) {
  let renderProps: NavProps = {
    text: text,
  };
  return comp(renderProps);
}

将与以下内容相同:

export default function Nav(props: NavProps & Comp<NavProps>) {
  let renderProps: NavProps = {
    text: props.text,
  };
  return props.comp(renderProps);
}

推荐阅读