0

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.

Artem Ibragimov
  • 463
  • 3
  • 17
  • Possible duplicate of [What is the purpose of template literals (backticks) following a variable definition in ES6?](https://stackoverflow.com/questions/53507972/what-is-the-purpose-of-template-literals-backticks-following-a-variable-defini) – Daniel Rearden Sep 20 '19 at 02:31

1 Answers1

1

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!
skovy
  • 4,535
  • 2
  • 14
  • 31