Apollo 服务器中的 Typescript 语法
Typescript Syntax in Apollo server
如您所知,在 appollo 服务器中,您可以通过将字符串传递到 gql 来定义服务器的架构。
const typeDefs = gql`
type Query {
getBtcRates: [BtcRate]
}
`'
但是gql是什么?是函数还是方法?
是定义
export const gql: (
template: TemplateStringsArray | string,
...substitutions: any[]
) => DocumentNode = gqlTag;
对我来说它更像是一个函数,但我不知道这种语法,所以想知道它到底是什么以及为什么这样写。
gql
使用称为 tagged templates and is not TypeScript specific. For another example, styled-components
的语法也依赖于此语法。
来自文档:
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.
这是如何工作的基本示例:
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!
如您所知,在 appollo 服务器中,您可以通过将字符串传递到 gql 来定义服务器的架构。
const typeDefs = gql`
type Query {
getBtcRates: [BtcRate]
}
`'
但是gql是什么?是函数还是方法?
是定义
export const gql: (
template: TemplateStringsArray | string,
...substitutions: any[]
) => DocumentNode = gqlTag;
对我来说它更像是一个函数,但我不知道这种语法,所以想知道它到底是什么以及为什么这样写。
gql
使用称为 tagged templates and is not TypeScript specific. For another example, styled-components
的语法也依赖于此语法。
来自文档:
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.
这是如何工作的基本示例:
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!