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

joh*_*pin 7 typescript reactjs

我目前正在使用 TypeScript 开发一个 React 项目,我遇到了一个非常愚蠢的问题,而且最重要的是非常烦人......

例如,我创建一个名为的虚拟组件Page,需要 apage类型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
Run Code Online (Sandbox Code Playgroud)

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

import Page, { Page } from './component/Page'  // ts-error: 'Duplicate identifier 'Page''
Run Code Online (Sandbox Code Playgroud)

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

art*_*pse 7

你的解决方案很接近。只需对两个对象使用相同的导出“样式”,以便可以将它们一起导入。页面将是值和类型的别名。

./component/Page.ts

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

export default Page
Run Code Online (Sandbox Code Playgroud)

./应用程序.ts

import Page from './component/Page'

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

Run Code Online (Sandbox Code Playgroud)

  • 这确实是一个好问题。我以前也遇到过这个问题,我选择了一个解决方法,给它起另一个名字。但我还是放不下。感谢@johannchopin的坚持,终于我也看到了这个可以接受的答案。然而,一个问题是使用声明合并意味着我无法将声明与组件分开,它必须位于同一模块中,对吧?这违背了将所有声明放在一处的最佳实践。对此,大家有什么意见吗? (2认同)