Issue with Generic Type Guard
I'm facing a problem while trying to create a generic type guard for various Token
types. The current implementation I have is as follows:
export function isToken<T extends Token>(token: any): token is T {
for (const key in keyof T) {
if (!(key in token) || typeof token[key] !== typeof T[key]) {
return false;
}
}
return true;
}
However, TypeScript is throwing errors stating that:
- in line
(1)
:
- indicating an issue with theCannot find name 'keyof'.ts(2304)
keyof
keyword - in line
(2)
:'T' only refers to a type, but is being used as a value here.ts(2693)
Any suggestions on how to resolve this?
Description of Tokens
The tokens represent different JWT payloads:
const type Token = {
userId: string;
}
const type LoginToken extends Token = {
role: 'User' | 'Admin'
}
const type EmailVerificationToken extends Token = {
email: string;
}
Current Approach for Type Guard
While I've been successful in creating specific token verification functions, there still exists a separate type guard for each token type:
// Example of individual token type check function
// Seeking to consolidate these into a single generic type guard
export function isVerificationToken(token: any): token is VerificationToken {
return typeof token.userId === 'string' && typeof token.email === 'string';
}
export function verifyVerificationToken(token: string) {
return verifyToken<VerificationToken>(token, isVerificationToken);
}
function verifyToken<T>(token: string, tokenTypeCheck: (token: any) => token is T) {
const decoded = jwt.verify(token, config.jwtSecret);
if (tokenTypeCheck(decoded)) {
return decoded;
}
return null;
}