简体   繁体   English

Object 输入 Typescript

[英]Object Type in Typescript

I am running a graphql mutation and depending on what the user inputs on the front end, I pass different variables in the graphql mutation using the input object.我正在运行 graphql 突变,根据用户在前端输入的内容,我使用input object 在 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,
        },
      })

However, I don't want to use input: any and want to be more specific.但是,我不想使用input: any并且想要更具体。 Generally, this is the input type that I am using in my mutation itself:通常,这是我在突变本身中使用的输入类型:

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

I have tried using this instead of any but it doesn't work.我试过用这个代替any ,但它不起作用。 I have also tried to use object but then I get errors like:我也尝试过使用object但后来我收到如下错误:

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

If depending on the input the data may exist or not, you can simply make them an optional property in the interface, that way you still get all the intellisense but if a property does not exist it won't throw an error.如果根据输入数据可能存在或不存在,您可以简单地将它们设置为界面中的可选属性,这样您仍然可以获得所有智能感知,但如果属性不存在,它不会引发错误。

So,所以,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM