简体   繁体   中英

Calling function with optional argument in TypeScript

I'm trying to patch graphql-cli 's get-schema function to print description using comment. I forked the library [ https://github.com/poernahi/graphql-cli] and edited src/cmds/get-schema.ts :

printSchema(newSchemaResult as GraphQLSchema)

becomes

printSchema(newSchemaResult as GraphQLSchema, {commentDescriptions: true})

When I run npm install , tsc did not like my meddling..

src/cmds/get-schema.ts(194,11): error TS2554: Expected 1 arguments, but got 2.

Now I really don't understand this error, because when I look at node_modules/graphql/utilities/schemaPrinter.js.flow , I see the function signature clearly indicates a second optional parameter.

type Options = {| commentDescriptions?: boolean |};

export function printSchema(schema: GraphQLSchema, options?: Options): string

I tried using undefined as the second parameter and still get the same error. I read the ts documentation and this is the right syntax to define optional param, even if it is written in flow.

Is this caused by mixing flow and typescript?

How did typescript get the argument list? I walked through the import chain and it pointed to the definition above.

What am I missing? Any workaround?

Thanks

What you are looking at are the flow type annotations. They have nothing to do, with what TypeScript picks up for the typings of the library. In the case of graphql the typings actually come from a community hosted typing repository which you can find here: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/graphql

When you take a look at the typing for the function you want to use, you can see, that the second argument is not added and therefore TypeScript doesn't know anything about it: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/graphql/utilities/schemaPrinter.d.ts#L4

So in order for TypeScript to properly know the second argument, you have to add it to the typings file over at DefinitelyTyped.

The TypeScript types do not specify an options parameter: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/graphql/utilities/schemaPrinter.d.ts#L4

So it looks like there is a discrepancy between Flow and TS as you suspected.

You could look into overriding the TS typings manually using declaration merging to define your own signature for the printSchema method. You have to be sure the printSchema method really accepts the second options argument though. Perhaps the flow typings are out of date?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM