如何在javascript中创建导出的类型定义的实例?

时间:2016-11-28 16:27:33

标签: javascript react-native es6-modules react-native-fbsdk

react-native-fbsdk(v0.3.0)在FBShareOpenGraphContent.js中定义了以下类型

export type ShareOpenGraphContent = {
  /**
   * The type of content to be shared is open graph content.
   */
  contentType: 'open-graph',

  /**
   * Common parameters for share content;
   */
  commonParameters?: ShareContentCommonParameters,

  /**
   * URL for the content being shared.
   */
  contentUrl?: string,

  /**
   * Open Graph Action to be shared.
   */
  action: ShareOpenGraphAction,

  /**
   * Property name that points to the primary Open Graph Object in the action.
   */
  previewPropertyName: string,
};

如何创建 ShareOpenGraphContent 的实例?

1 个答案:

答案 0 :(得分:1)

类型不是你可以实例化的东西。假设您正在使用流,如果您运行flow来检查潜在的类型错误,它们仅仅是有用的。它们还使一些IDE(如WebStorm)能够根据类型向您显示建议。因此,您可以在函数和变量声明中使用这些类型。例如:

function createOpenGraphContent(contentType: string, action: ShareOpenGraphAction, previewPropertyName : string) : ShareOpenGraphContent {
    return {
        contentType: contentType,
        action: action,
        previewPropertyName: previewPropertyName,
        randomKey: 'something' // If you include this, flow will raise an error, since the definition of ShareOpenGraphContent does not include randomKey.
    }
}

您可以使用变量执行类似操作:

var aNumber : Number = 10;
aNumber.trim(); // This will raise an error when running flow, as Number does not have the trim method.

至于你的原始问题,如果你想创建一个符合ShareOpenGraphContent类型的对象,你只需要定义所有必需的键,如果你需要它们,可选的那些键,但绝不能用别的东西。无论如何,你的代码运行正常,但流程会抱怨。

如果您正在运行不同的基于类型的JavaScript(例如TypeScript),它可以归结为基本相同,只是在转换时可能会出现错误,而不是可选地运行检查程序。

相关问题