gpt4 book ai didi

typescript - 不公开泛型类型的函数的类型注释

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:12 27 4
gpt4 key购买 nike

我正在使用 react-native-navigation@types/react-native-navigation .它的工作方式是所有注册的 React Native 组件都会自动获得 this.props.navigator。 .

navigator有一个 push方法,但它不允许任何类型参数。它有一个名为 passProps 的属性它允许您将属性传递给您正在导航到的页面,但是无法注释您正在传递的 Prop 类型,这些 Prop 应该与您正在导航到的屏幕的 Prop 相匹配。例如:

export interface BioProps { username: string }
export class BioScreen extends React.Component<BioProps> {}

this.props.navigator.push({
screen: 'bio.BioScreen',
title: 'foo',
passProps: {
username,
}
});

在这种情况下,我想要 passPropsBioProps 的类型相同为了类型安全。但是,没有什么比 .push<BioProps>这将使您能够做到这一点。

当类型安全未内置到定义中时,是否有任何方法可以强制执行类型安全?

最佳答案

您可以扩充模块中的 Navigator 接口(interface),以添加一个通用重载,该重载将强制 props 为特定类型:

// react-native-navigation-augmented.ts
import { Navigation, NavigationComponentProps } from 'react-native-navigation';
declare module 'react-native-navigation'{
export interface Navigator {
push<T>(params: PushedScreen & { passProps: T }): void
}
}


// Otherfile.ts
/// <reference path="./react-native-navigation-augmented.ts" />
this.props.navigator.push<BioProps>({
screen: 'bio.BioScreen',
title: 'Pushed Screen',
// Will cause an error if username is not present or of a different type
passProps: {
username: ""
}
});

关于typescript - 不公开泛型类型的函数的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48757365/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com