I am currently trying to implement a react app with Auth0 for authentication, and i am new to typescript.
Have tried the code below in my Auth.js
and it works fine but when i tried to migrate my Auth.js
file to Auth.ts
i get the red squiggly with the errors
Property 'history' does not exist on type Auth
Property 'userProfile' does not exist on type Auth etc
import auth0 from "auth0-js";
const REDIRECT_ON_LOGIN = "redirect_on_login";
export default class Auth {
constructor(history) {
this.history = history;
this.userProfile = null;
this.requestedScopes = "openid profile email";
this.auth0 = new auth0.WebAuth({
domain: process.env.REACT_APP_AUTH0_DOMAIN,
clientID: process.env.REACT_APP_AUTH0_CLIENT_ID,
redirectUri: process.env.REACT_APP_AUTH0_CALLBACK_URL,
audience: process.env.REACT_APP_AUTH0_AUDIENCE,
responseType: "token id_token",
scope: this.requestedScopes
});
}
login = () => {
localStorage.setItem(
REDIRECT_ON_LOGIN,
JSON.stringify(this.history.location)
);
this.auth0.authorize();
};
handleAuthentication = () => {
this.auth0.parseHash((err, authResult) => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult);
const redirectLocation =
localStorage.getItem(REDIRECT_ON_LOGIN) === "undefined"
? "/"
: JSON.parse(localStorage.getItem(REDIRECT_ON_LOGIN));
this.history.push(redirectLocation);
} else if (err) {
this.history.push("/");
alert(`Error: ${err.error}. Check the console for details`);
console.log(err);
}
localStorage.removeItem(REDIRECT_ON_LOGIN);
});
};
I want to be able to implement auth0 authentication with react & typescript
You need to install Auth0 types:
npm i @types/auth0
or this one:
npm i @types/auth0-js
and if these solutions doesn't work exclude the Auth0
package in your tsconfig.js
file like this:
"exclude": [
"node_modules/auth0-js"
]
just find the Auth0 directiory and exclude it.
in typescript "class" is also a type. So when you are using "class", you are creating two things.
1- javascript class function
2- typescript type
Since class is treated as type too, you have to specify the types of properties and methods.
class Auth{
history:findTheTypeOfHistory;
userProfile:typeofUserProfile
.
.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.