I have a problem with my typescript usage.
First, let me tell you what I want to do:
First of all, I have an advanced user login system that manages user logins in the backend, so I need to include many file systems in order to integrate it into the react side. One of them is the auth.tsx
file located under the actions file. The purpose of this file is to make the necessary API calls to the server and transfer the information there to the form design, so I will have a much neater code structure. But unfortunately, because there is typescript in the system, I get some errors and I can't figure out why. Can you help?
this is piece of code from auth.tsx file
export const facebookAuthenticate = (state:string, code:string) => async dispatch => {
if (state && code && !localStorage.getItem('access')) {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const details = {
'state': state,
'code': code
};
const formBody = Object.keys(details).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(details[key])).join('&');
try {
const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/o/facebook/?${formBody}`, config);
dispatch({
type: FACEBOOK_AUTH_SUCCESS,
payload: res.data
});
dispatch(load_user());
} catch (err) {
dispatch({
type: FACEBOOK_AUTH_FAIL
});
}
}
};
In the dispatch parameter on this code, the dispatch parameter has an implicit type 'any'. I get the error also in encodeURIComponent(details[key])) ,
the expression of type 'string' is '{ state: string; code: string; Element has type 'any' implicitly because it cannot be used to index type '}'.
'{ state: string; code: string; I am getting the error ts(7053) not found directory signature with parameter of type 'string' on type '}'.
Please help me
The TS type of return value for Object.keys() is string[], see below TS type definition:
lib.es5.d.ts:
keys(o: object): string[];
But the type of the key should be 'state' | 'code' rather than any string. So you should Type Assertions to specify a more specific type.
const details = {
'state': state,
'code': code
};
const formBody = (Object.keys(details) as (keyof typeof details)[]).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(details[key])).join('&');