2016-11-28 64 views
0

的反应,本机fbsdk(v0.3.0)定义FBShareOpenGraphContent.js如何在JavaScript中创建导出类型定义的实例?

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

类型不是你可以实例化的东西。假设您正在使用流程,如果您运行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),则归结为本质上相同,只是在转码时可能会出现错误,而不是可选地运行检查程序。

相关问题