第一次使用Typescript时,我在贴图内部渲染一个组件,如下所示:

interface chatInterface {
  sender: string;
  avatar: string;
  content: string;
  time: string;
}
<>    
  {eachUser?.chats.map((item) =>
                  item.messages.map((obj: chatInterface, index: number) => {
                    return <ChatPage key={index} message={obj} />;
                  })
                )}
</>

ChatPage组件是:

function ChatPage(props: { message: chatInterface }) {
  const { sender, avatar, content, time } = props.message;
  return (
      <div>
        <ul>
          <li>
            <strong>{sender}:</strong> {content} at:{time}
          </li>
        </ul>
    </div>
  );
}

它工作得很好,但我想为ChatPage组件创建一个页面,但我不知道应该如何在react路由中导入它.这是我的应用程序.tsx组件:

<Router>
        <Navbar />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/profile" element={<Profile />} />
          <Route path="/chat" element={<ChatPage />} />
        </Routes>
      </Router>

上面说

Property 'message' is missing in type '{}' but required in type '{ message: chatInterface; }'

提前感谢

推荐答案

看起来ChatPage组件缺少更好的类型声明.错误是messageprops 是必需的,并且丢失了.换句话说,它不是可选的props .

message设为可选属性,并在组件中处理destructuring fallback值.

示例:

interface chatPageInterface {
  message?: chatInterface;
}

function ChatPage(props: chatPageInterface) {
  const { sender, avatar, content, time } = props.message || {};
  return (
      <div>
        <ul>
          <li>
            <strong>{sender}:</strong> {content} at:{time}
          </li>
        </ul>
    </div>
  );
}

Typescript相关问答推荐

无法从应用程序内的库导入组件NX Expo React Native

有没有一种方法可以在保持类型的可选状态的同时更改类型?

异步动态生成Playwright测试,显示未找到测试

在TypeScrip的数组中判断模式类型

如何重构长联合类型?

是否可以从函数类型中创建简化的类型,go 掉参数中任何看起来像回调的内容,而保留其余的内容?

使用动态输出类型和泛型可重用接口提取对象属性

将带有样式的Reaction组件导入到Pages文件夹时不起作用

在TypeScript中扩展重载方法时出现问题

为什么TypeScrip不能解析对象析构中的赋值?

tailwind css未被应用-react

如果判断空值,则基本类型Gaurd不起作用

在Thunk中间件中输入额外参数时Redux工具包的打字脚本错误

设置不允许相同类型的多个参数的线性规则

在TypeScript中,如何通过一系列过滤器缩小类型?

编剧- Select 下拉框

如何在TypeScript中描述和实现包含特定属性的函数?

如何知道使用TypeScript时是否在临时工作流内运行

如何根据Typescript 中带有泛型的对象嵌套键数组获取数组或对象的正确类型?

为什么 Typescript 无法正确推断数组元素的类型?