简体   繁体   中英

Type GQLSchema is not assignable to type undefined

Okay... I am trying to develop a GraphQL solution to attach several type definitions to express-graphql graphqlHTTP() typeDef property without worrying about creating a single schema for each type or nesting strings.

My issue here is whenever I pass an array of arguments to function createSchema() it displays an error on the second item of the array (yes, not in the first):错误 Note: Not sure if the second problem is an actual error or just a warning. I guess it is warning.

So, this is the function itself:

  static createSchema(typeDefs: GQLSchema | [GQLSchema]): string {
    let schema = '';

    if (Array.isArray(typeDefs)) {
      typeDefs.forEach((typeDef) => {
        schema += GQLHTTPTools.addSchema(typeDef);
      });
    } else {
      schema = GQLHTTPTools.addSchema(typeDefs);
    }

    return schema;
  }

  // just in case:
  private static addSchema(typeDef: GQLSchema): string {
    const { types } = typeDef;
    let schema = '';

    if (types.Query !== undefined) {
      schema += `type Query {\n\t${types.Query}\n}\n`;
      delete types.Query;
    }
    if (types.Mutation !== undefined) {
      schema += `type Mutation {\n\t${types.Mutation}\n}\n`;
      delete types.Mutation;
    }
    if (types.Custom !== undefined) {
      schema += types.Custom.map((type) => {
        const key = Object.keys(type)[0];
        const val = Object.values(type)[0];
        return `type ${key} {\n\t${val}\n}`;
      });
    }

    return schema;
  }

Not sure if it's important, but this is the GQLSchema class definition:

export default class GQLSchema {
  constructor(public totalTypes: number, public totalCustomTypes: number, public types: GQLType) {}
}

If I do pass a single GQLSchema object it works... but not if I use a GQLSchema array. Not sure why isn't working. Any clues?

In TypeScript [X] is a Tuple

Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same.

So [X] means an array with a length of exactly one where the first element is of the type X . [X, Y] means an array with a length of exactly two where the first element is of type X and the second element is of type Y . And so on.

If your intent is to type an array of any length where every element is a specific type, use an Array instead: X[] or Array<X> (these are equivalent).

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