打字稿:如何使用通用参数作为对象键

好主意

是否可以编写一个接受字符串常量作为其参数之一并将其用作对象键的接口?

例如,假设我发出了两个不同的GraphQL请求,两个请求都返回a User,但是使用不同的键名:

const userByIdResult = {
  data: {
    userById: {
       id: 123,
       username: 'joseph'
    }
  }
}

const userByUsernameResult = {
  data: {
    userByUsername: {
       id: 123,
       username: 'joseph'
    }
  }
}

我可以想象编写一个通用接口会像这样:

interface GraphQLResponse<QueryKey, ResponseType> {
  data: {
    [QueryKey]: ResponseType
  }
}

interface User {
    username: string
    id: string
}

type UserByIdResponse = GraphQLResponse<'userById', User>
type UserByUsernameResponse = GraphQLResponse<'userByUsername', User>

但是,这不起作用

肖恩·卢汀(Shaun Luttin)

你近了 这属于“映射类型类别您需要进行两项更改:

  1. QueryKey extends string
  2. key in QueryKey
interface GraphQLResponse<QueryKey extends string, ResponseType> {
    data: {
        [key in QueryKey]: ResponseType;
    }
}

interface User {
    username: string;
    id: number;
}

type UserByIdResponse = GraphQLResponse<'userById', User>;
type UserByUsernameResponse = GraphQLResponse<'userByUsername', User>;

用法示例

const userByIdResult: UserByIdResponse = {
    data: {
        userById: {
            id: 123,
            username: 'joseph'
        }
    }
}

const userByUsernameResult: UserByUsernameResponse = {
    data: {
        userByUsername: {
            id: 123,
            username: 'joseph'
        }
    }
}

const userByIdResultBoom: UserByIdResponse = {
    data: {
        userByUsername: {
            id: 123,
            username: 'joseph'
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章