![](/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.