2016-11-28 63 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),則歸結爲本質上相同,只是在轉碼時可能會出現錯誤,而不是可選地運行檢查程序。

相關問題