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

How do I create an instance of an exported type definition in javascript?

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 的实例?

类型不是您可以实例化的东西。假设您正在使用流,它们仅在您 运行 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),它归结为基本相同,只是在转译时可能会出现错误当可选地 运行ning 一个检查器时。