简体   繁体   中英

Typescript Syntax in Apollo server

As you know in appollo server you can define the server's schema by passing a string into gql.

const typeDefs = gql`
type Query {
  getBtcRates: [BtcRate]
}
`'

But what is gql? Is it a function or a method?

It's definition

export const gql: (
  template: TemplateStringsArray | string,
  ...substitutions: any[]
) => DocumentNode = gqlTag;

To me it looks more like a function, but this syntax is unknown to me, so wonder what exactly it is and why this is written this way.

gql is using syntax called tagged templates and is not TypeScript specific. For another example, styled-components also relies on this syntax.

From the docs:

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

A basic example of how this works:

 var variable = 'world'; function myTag(strings, exp) { var str0 = strings[0]; // "Hello " var str1 = strings[1]; // ";" return `${str0}${exp}${str1}`; } var output = myTag`Hello ${ variable }.`; console.log(output); // Hello world!

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