避免 TypeScript 中对象和接口之间的重复标识符

IT技术 reactjs typescript
2021-05-09 17:46:15

我目前正在使用 TypeScript 进行 React 项目,但遇到了一个非常愚蠢的问题,而且非常烦人……

例如,我创建了一个虚拟组件Page,它需要一个page类型Page作为props:

interface Props {
  page: Page
}

export interface Page {
  id: number
  category: PageCategory
  path: string
  name: string
}

const Page: React.FunctionComponent<Props> = (props) => {
  ...
  return (
    ...
    <h1>{ props.page.name }<h1/>
    ...


export default Page

到目前为止没有问题,但是一旦我决定导入具有以下类型的组件,它们就会出现:

import Page, { Page } from './component/Page'  // ts-error: 'Duplicate identifier 'Page''

所以为了避免这个问题,我在I我所有的接口中添加了前缀IPage但我相信有一种更优雅的方法来做到这一点。你怎么处理?

2个回答

您的解决方案很接近。只需对两个对象使用相同的导出“样式”,即可将它们一起导入。Page 将是 Value 和 Type 的别名。

./component/Page.ts

interface Page { ... }
const Page: ...

export default Page

./App.ts

import Page from './component/Page'

const pageData: Page = { id: ... }
const pageComponent = Page 

主要问题是因为您的接口和组件具有相同的名称,并且您都在导出它。

最简单的解决方案是重命名您的接口/类型。只需在其中添加单词Props即可使其仍然有意义(或您喜欢的任何后缀)

interface Props {
  page: PageProps
}

export interface PageProps {
  id: number
  category: PageCategory
  path: string
  name: string
}

const Page: React.FunctionComponent<Props> = (props) => {
  ...
  return (
    ...
    <h1>{ props.page.name }<h1/>
    ...


export default Page

所以像这样导入它不会有问题

import Page, { PageProps } from './component/Page'