I'm trying to implement a generic function interface and I cannot make it work.
IToken.ts
export interface IToken { token: string; expires: number; }
ITokenMapper.ts
export interface ITokenMapper { <T>(apiResult: any): T; }
tokenMapper.ts
import {ITokenMapper} from "./interfaces/ITokenMapper"; import {IToken} from "./interfaces/IToken"; export const tokenMapper: ITokenMapper = function <IToken>(apiResult: any): IToken { if(apiResult.token && apiResult.expires) { return {token: apiResult.token as string, expires: apiResult.expires as number} } throw new Error('Unable to parse token'); };
Here is a screenshot from tokenMapper.ts
saying IToken import is unused but I should have a use for it:
Edit : Using Typescript 3.0.3
I believe you can accomplish your typing with a generic interface ITokenMapper<T>
interface IToken {
token: string;
expires: number;
}
interface ITokenMapper<T> {
(apiResult: T): T;
}
const tokenMapper: ITokenMapper<IToken> = function (apiResult) {
if(apiResult.token && apiResult.expires) {
return { token: apiResult.token as string, expires: apiResult.expires as number};
}
throw new Error('Unable to parse token');
};
From: https://www.typescriptlang.org/docs/handbook/generics.html#generic-types
So here is what I changed to make it work
ITokenMapper.ts -> IMapper.ts renamed and updated
export type IMapper<T> = (apiResult: any) => T;
tokenMapper.ts -> abpTokenMapper.ts renamed and updated
import { IMapper } from "../../utils/IMapper"; import { IToken } from "../interfaces/IToken"; export const abpTokenMapper: IMapper<IToken> = (apiResult: any) => { if (apiResult.accessToken && apiResult.expireInSeconds) { return { token: apiResult.accessToken as string, expires: apiResult.expireInSeconds as number } } throw new Error('Unable to parse token'); };
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.