GraphQL解析器上的从属条件类型

时间:2019-09-25 12:37:11

标签: typescript graphql

我想为类型安全的GraphQL解析器编写TS类型。我有一个简单的架构:

type User {                                                                            
  name: String!
  likes: Number!
}

type Query {
  users(id: Number): User!
}

因此,Resolvers的{​​{1}}类型与Query.users解析器的类型相结合,应该返回完整的User.*

我可以像这样用手手写

User

并确保我可以编译有效的实现:

type User = {
  name: string
  likes: number
}

type Resolvers =
{
  Query: { user: (id: number) => User },
  User?: { [F in keyof User]?: () => User[F] }
} | {
  Query: { user: (id: number) => Omit<User, "likes"> },
  User: { 
    name?: () => User["name"],
    likes: () => User["likes"]
  }
} | {
  Query: { user: (id: number) => Omit<User, "name"> },
  User: { 
    name: () => User["name"],
    likes?: () => User["likes"]
  }
} | {
  Query: { user: (id: number) => Omit<User, "name" | "likes"> },
  User: { 
    name: () => User["name"],
    likes: () => User["likes"]
  }
}

并在缺少的字段上显示错误:

const valid1: Resolvers = {
  Query: {
    user: () => ({ name: "John" }),
  },
  User: {
    likes: () => 1
  }
}

const valid2: Resolvers = {
  Query: {
    user: () => ({}),
  },
  User: {
    name: () => "John",
    likes: () => 2,
  }
}

const valid3: Resolvers = {
  Query: {
    user: () => ({ name: "John", likes: 3 }),
  }
}

带有所有这样写的特定分支的联合类型不会扩展到更大的模式。 有没有一种方法可以编写生成通用组合的泛型 const invalid: Resolvers = { Query: { user: () => ({}), }, User: { likes: () => 0 } // Property 'name' is missing in type '{ likes: () => number; }' but required in type '{ name: () => string; likes: () => number; }' } 类型?

0 个答案:

没有答案