Javascript Typescript中的对象类型
我正在运行graphql变异,根据用户在前端输入的内容,我使用Javascript Typescript中的对象类型,javascript,reactjs,typescript,object,graphql,Javascript,Reactjs,Typescript,Object,Graphql,我正在运行graphql变异,根据用户在前端输入的内容,我使用input对象在graphql变异中传递不同的变量 const [updateUser] = useMutation<UpdateUserReponse>(UPDATE_USER); let submitForm = ( email: string, firstName: string, lastName: string, newEmail: string, phoneNumb
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,
},
})
我试过用这个代替any
,但它不起作用。我还尝试使用对象
,但随后出现如下错误:
Property 'firstName' does not exist on type 'object'.ts(2339)
如果数据可能存在或不存在取决于输入,您可以简单地将其作为接口中的可选属性,这样您仍然可以获得所有intellisense,但如果属性不存在,则不会抛出错误 所以
此外,您只需通过执行
if(firstName){stuff}
检查值是否存在,无需专门使用!==运算符,因为非空字符串值为truthy
Property 'firstName' does not exist on type 'object'.ts(2339)
interface UpdateUserInput {
email: String;
firstName?: String;
lastName?: String;
phoneNumber?: String;
}