![](/img/trans.png)
[英]Why can't Typescript infer function argument types for optional arguments?
[英]Calling function with optional argument in TypeScript
我正在嘗試修補graphql-cli
的get-schema
函數以使用注釋打印描述。 我分叉了庫[ https://github.com/poernahi/graphql-cli]並編輯了src/cmds/get-schema.ts
:
printSchema(newSchemaResult as GraphQLSchema)
變
printSchema(newSchemaResult as GraphQLSchema, {commentDescriptions: true})
當我運行npm install
, tsc
不喜歡我的插手..
src/cmds/get-schema.ts(194,11): error TS2554: Expected 1 arguments, but got 2.
現在我真的不明白這個錯誤,因為當我查看node_modules/graphql/utilities/schemaPrinter.js.flow
,我看到函數簽名清楚地表明了第二個可選參數。
type Options = {| commentDescriptions?: boolean |};
export function printSchema(schema: GraphQLSchema, options?: Options): string
我嘗試使用undefined
作為第二個參數仍然得到相同的錯誤。 我閱讀了ts文檔,這是定義可選參數的正確語法,即使它是用流寫的。
這是由混合流和打字稿引起的嗎?
打字稿是如何獲得參數列表的? 我走過了進口鏈,它指出了上面的定義。
我錯過了什么? 任何解決方法?
謝謝
您正在查看的是流類型注釋。 它們無關,TypeScript選擇了庫的類型。 在graphql
的情況下, graphql
實際上來自社區托管的輸入存儲庫,你可以在這里找到: https : //github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/graphql
當您查看要使用的函數的類型時,您可以看到第二個參數未添加,因此TypeScript對此一無所知: https : //github.com/DefinitelyTyped/DefinitelyTyped/斑點/主/類型/ graphql /公用事業/ schemaPrinter.d.ts#L4
因此,為了讓TypeScript正確地知道第二個參數,您必須將它添加到DefinitelyTyped的typings文件中。
TypeScript類型不指定options
參數: https : //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/graphql/utilities/schemaPrinter.d.ts#L4
所以看起來你懷疑Flow與TS之間存在差異。
您可以使用聲明合並來手動覆蓋TS類型,以便為printSchema
方法定義自己的簽名。 您必須確保printSchema
方法確實接受第二個options
參數。 也許流量類型已經過時了?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.