SomethingOn SomethingOn - 1 year ago 65
Javascript Question

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

The react-native-fbsdk (v0.3.0) defines the following type in 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,

How do I create an instance of ShareOpenGraphContent?

Answer Source

Types are not something you can instantiate. Assuming you are using flow, they are merely helpful if you run flow to check for potential type errors. Also they enable some IDEs (like WebStorm) to show you suggestions based on types. What you can do thus is use those types in your function and variable declarations. For instance:

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.

You can do something similar with variables:

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

As for your original question, if you want to create an object that complies with the type ShareOpenGraphContent, you just have to define all the required keys and if you need them, the optional ones, but never something else. Your code would run fine anyway, but flow will complain.

In the event that you are running a different type-based JavaScript (such as TypeScript), it boils down to essentially the same, only that errors might arise at transpilation time instead of when optionally running a checker.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download