Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - How do I type parseLiteral parameter in date scalar?

How do I type ast?

import { CustomScalar, Scalar } from '@nestjs/graphql'
import { Kind } from 'graphql'
export class DateScalar implements CustomScalar<number, Date> {
  description = 'Date custom scalar type'

  parseValue(value: number): Date {
    return new Date(value) // value from the client
  }

  serialize(value: Date): number {
    return value.getTime() // value sent to the client
  }

  parseLiteral(ast): Date { // <-- ???
    if (ast.kind === Kind.INT) {
      return new Date(ast.value)
    }
    return null
  }
}

I tried to use

interface AST {
  kind: string
  value: number
}

but then I do get the error

  Property 'parseLiteral' in type 'DateScalar' is not assignable to the same property in base type 'CustomScalar<number, Date>'.
    Type '(ast: AST) => Date' is not assignable to type 'GraphQLScalarLiteralParser<Date>'.
      Types of parameters 'ast' and 'valueNode' are incompatible.
        Type 'ValueNode' is not assignable to type 'AST'.
          Property 'value' is missing in type 'VariableNode' but required in type 'AST'
question from:https://stackoverflow.com/questions/65644162/how-do-i-type-parseliteral-parameter-in-date-scalar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, by looking at Nest's custom-scalar interface we can see that parseLiteral is of type GraphQLScalarLiteralParser<K> from graphql. After digging around GraphQL-js's types I found this definition where ast is also called a ValueNode. A ValueNode is a union of other value nodes that contains things like NullValueNode and ObjectValueNode which don't have value as properties, hence why you're getting that error.

All of that preface and linking to say: if you want to type it, use import { ValueNode } from 'graphql'; and use the type ValueNode. By using ast.Kind === Kind.INT the ast will get casted to an IntValueNode which has the field value as a property. Should clear up any type issues you've got


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...