Home > Net >  How to return a Typescript class return as oneliner
How to return a Typescript class return as oneliner

Time:09-28

Hi have a class and use an interface

interface myInterface {
    readonly exp: number;
    readonly iat: number;
    readonly auth_time: number;
    readonly jti: string;

}

export class MyClass {
    static async scope(token: string): Promise<any> {
        const scope: myInterface = await jwt_decode(token);
        return scope;
    }
}

how can i make

        const scope: myInterface = await jwt_decode(token);
        return scope;

as a oneliner?

Thanks in advance. Any help is welcome.

CodePudding user response:

You could use the as keyword to cast the typing of variable scope from ReturnType<typeof jwt_decode> to myInterface by:

static async scope(token: string) {
  return await jwt_decode(token) as myInterface;
}

Or you could even write it like this by arrow function:

static scope = (token: string) => jwt_decode(token) as Promise<myInterface>;

CodePudding user response:

Actually you don't need anything special, just specify the return type of the method:

static async scope(token: string): Promise<myInterface> {
  return await jwt_decode(token);
}

CodePudding user response:

In Typescript 4.9 (not released yet) you may be able to use the new satisfies keyword.

static async scope(token: string): Promise<myInterface> {
  return await jwt_decode(token) satisfies myInterface;
}

Unlike as, it does perform typechecking, but it doesn't change the inferred type (unlike in your example). But by specifying that the method returns a Promise<myInterface>, you get the correct type anyway.

  • Related