【发布时间】:2020-03-09 13:49:28
【问题描述】:
当我正在学习 Typescript 时,我不确定如何描述这一点。
我面临的问题如下。应用程序中有两个接口。一篇用于博客文章,一篇用于活动文章:
type Category = "Foo" | "Bar";
// 1
export interface PostBlog {
title: string;
author: string;
categories: Array<Category>;
}
// 2
export interface PostEvent {
title: string;
date: Date;
}
现在传递给组件的数据如下所示:
import Blogs from "./Blogs";
import Events from "./Events";
const blogPosts = [{ document: { data: { title: "Blogpost title", author: "John Doe" } }, slug: "./blogpost-title" }];
const eventPosts = [{ document: { data: { title: "Event title", date: "01-01-2020" }}, slug: "./event-title" }];
export default function App() {
return (
<div className="App">
<Blogs posts={blogPosts} />
<Events posts={eventPosts} />
</div>
);
}
然后在组件中:
import * as React from "react";
import { Data } from "../shared.types";
interface BlogPosts {
posts: Data[];
}
const Blogs: React.FC<BlogPosts> = ({ posts }) => {
return (
<ul>
{posts.map(({ document: { data } }) => (
<li>
Title: {data.title}
Author: {data.author} // produces the error
</li>
))}
</ul>
);
};
export default Blogs;
所以尝试是:
export interface Data {
document: {
data: PostBlog | PostEvent; // use it here
isEmpty?: boolean;
excerpt?: string;
};
slug: string;
}
但是,Typescript 通知这是不允许的,因为它们具有不共同的属性:
Property 'author' does not exist on type 'PostBlog | PostEvent'.
Property 'author' does not exist on type 'PostEvent'.ts(2339)
【问题讨论】:
标签: reactjs typescript