最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Static members cannot reference class type parameters.ts - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Apr 21, 2023 at 22:39 A1rPun 16.9k8 gold badges59 silver badges92 bronze badges asked Jan 20, 2021 at 7:02 Mr-ProgramerMr-Programer 5613 gold badges10 silver badges23 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论