如何在react-navigation v6中覆盖全局RootParamList



react-navigation v6的升级指南:

https://reactnavigation.org/docs/upgrading——从- 5. - x/# ability-to-specify-a-type-for-root-navigator-when-using-typescript

说明你可以使用

declare global {
namespace ReactNavigation {
interface RootParamList extends RootStackParamList {}
}
}

在代码的某个地方为所有钩子全局设置RootParamList。

但是,当我尝试包含代码片段并设置参数列表时,我得到的都是

Duplicate identifier 'RootParamList'.ts(2300)
types.d.ts(5, 19): 'RootParamList' was also declared here

显然,类型已经声明,我试图覆盖它,但这似乎是不可能的。

如何重写而不导致类型错误?

我遇到了这个问题,这是因为我没有按照建议使用完全相同的代码片段。我使用eslint,它会声明"一个没有声明成员的接口等同于它的超类型",在我的例子中,vim会自动将这个变成:

declare global {
namespace ReactNavigation {
interface RootParamList extends RootStackParamList {}
}
}

这:

declare global {
namespace ReactNavigation {
type RootParamList = RootStackParamList;
}
}

问题是react-navigation使用接口声明RootParamList。在这种情况下,我的RootParamList实际上是一个声明。

为了解决这个问题,我只需要确保使用一个接口并禁用@typescript-eslint/no-empty-interface规则:

declare global {
namespace ReactNavigation {
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface RootParamList extends RootStackParamList {}
}
}

我希望这对你有帮助!

最新更新