Mr-Programer
Mr-Programer

Reputation: 561

Static members cannot reference class type parameters.ts

I have this generic class and I want to use that generic parameters:

export class OperationResult<TResult>
{

    public success: boolean;
    public message: string;
    public result: TResult;

    constructor(success: boolean, message: string, result: TResult) {
        this.success = success;
        this.message = message;
        this.result = result;
    }

    public static BuildSuccessResult(message: string, result: TResult): OperationResult<TResult> {
        return new OperationResult<TResult>(true, message, result);
    }
}

but it show me this error for the BuildSuccessResult function:

Static members cannot reference class type parameters.ts

How can I return a generic value on a static function?

Upvotes: 5

Views: 2816

Answers (1)

Nishant
Nishant

Reputation: 55856

Your static method should also accept the generic like this:

See TS Playgrond: https://tsplay.dev/rw2ljm

public static BuildSuccessResult<TResult>(message: string, result: TResult): OperationResult<TResult> {
    return new OperationResult<TResult>(true, message, result);
}

Since the static method can be called without class instance, the method has to be generic. You would's require <TResult> part if the method wasn't static, because in that case, TResult can be inferred from the instance.

There is a lengthy discussion on TypeScript repo.

Upvotes: 7

Related Questions