【问题标题】:Type annotation for function that doesn't expose a generic type不公开泛型类型的函数的类型注释
【发布时间】:2018-07-23 06:22:49
【问题描述】:

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

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

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&lt;BioProps&gt; 这样的东西可以让你这样做。

在定义中没有内置类型安全时,有什么方法可以强制执行类型安全?

【问题讨论】:

    标签: typescript react-native react-native-navigation


    【解决方案1】:

    您可以从模块中扩充Navigator 接口以添加通用重载,强制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: ""
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-13
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      相关资源
      最近更新 更多