簡體   English   中英

Object 輸入 Typescript

[英]Object Type in Typescript

我正在運行 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,
        },
      })

但是,我不想使用input: any並且想要更具體。 通常,這是我在突變本身中使用的輸入類型:

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

我試過用這個代替any ,但它不起作用。 我也嘗試過使用object但后來我收到如下錯誤:

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

如果根據輸入數據可能存在或不存在,您可以簡單地將它們設置為界面中的可選屬性,這樣您仍然可以獲得所有智能感知,但如果屬性不存在,它不會引發錯誤。

所以,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM