【问题标题】:Object Type in TypescriptTypescript 中的对象类型
【发布时间】:2020-07-16 21:28:51
【问题描述】:

我正在运行 graphql 突变,根据用户在前端输入的内容,我使用 input 对象在 graphql 突变中传递不同的变量。

const [updateUser] = useMutation<UpdateUserReponse>(UPDATE_USER);

  let submitForm = (
    email: string,
    firstName: string,
    lastName: string,
    newEmail: string,
    phoneNumber: string,
  ) => {
    setIsSubmitted(true);

    if (email && (firstName || lastName || newEmail || phoneNumber)) {
      const input: any= {};
      if (firstName !== '') {
        input.firstName = firstName;
      }
      if (lastName !== '') {
        input.lastName = lastName;
      }
      if (newEmail !== '') {
        input.email = newEmail;
      }
      if (phoneNumber !== '') {
        input.phoneNumber = phoneNumber;
      }
      updateUser({
        variables: {
          email: email,
          input: input,
        },
      })

但是,我不想使用input: any,而是想更具体一些。通常,这是我在突变本身中使用的输入类型:

interface UpdateUserInput {
  email: String;
  firstName: String;
  lastName: String;
  phoneNumber: String;
}

我试过用这个代替any,但它不起作用。我也尝试过使用object,但随后出现如下错误:

Property 'firstName' does not exist on type 'object'.ts(2339)

【问题讨论】:

  • 另外,你可以通过if (firstName) { stuff }简单地检查一个值是否存在,不需要专门使用!==运算符,因为非空字符串值是真实的

标签: javascript reactjs typescript object graphql


【解决方案1】:

如果根据输入数据可能存在或不存在,您可以简单地将它们设置为界面中的可选属性,这样您仍然可以获得所有智能感知,但如果属性不存在,它不会抛出错误。

所以,

interface UpdateUserInput {
  email: String;
  firstName?: String;
  lastName?: String;
  phoneNumber?: String;
}

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 2018-04-04
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 2023-04-01
    • 2021-04-25
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多