5

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.