【问题标题】:How to initialize a readonly/private value in typescript using a setter?如何使用设置器在打字稿中初始化只读/私有值?
【发布时间】:2021-11-30 19:46:59
【问题描述】:

相关代码的一些背景知识:我正在尝试实现一个便于为用户初始化的配置类。为此,我的配置将实现配置接口的对象作为构造函数参数,而配置类处理默认值、验证等内容。

import Uri from '../Uri'

export default interface BaseUriConfigurationInterface
{
    uri: Uri | string
    mergePath?: boolean
    mergeQuery?: boolean
    defaultScheme?: 'http' | 'https' | null
    overrideScheme?: boolean
};

在配置中,uri 是唯一没有默认值的配置选项。

import ConfigurationInterface from '../contract/BaseUriConfigurationInterface'
import Uri from '../Uri'
import UriSyntaxError from '../error/UriSyntaxError'
import ConfigurationError from '../error/ConfigurationError'

export default class BaseUriConfiguration implements ConfigurationInterface
{
    private _uri: Uri
    readonly mergePath: boolean
    readonly mergeQuery: boolean
    readonly defaultScheme: 'http' | 'https' | null
    readonly overrideScheme: boolean

    constructor(config : ConfigurationInterface)
    {
        this.mergePath = true
        this.mergeQuery = false
        this.defaultScheme = null
        this.overrideScheme = false

        Object.assign(this, config);
    }

    public get uri() : Uri
    {
        return this._uri
    }

    private set uri(uri: Uri | string)
    {
        if(typeof uri === 'string') {

            try {
                uri = new Uri(uri)
            }
            catch(error) {
                if(! (error instanceof UriSyntaxError)) {
                    throw error
                }

                const msg = `Invalid base uri given. See previous error for more details.`
                throw new ConfigurationError(msg, error)
            }
        }

        this._uri = uri
    }
}

这里的想法是构造函数设置配置选项的所有默认值,而设置器用于改变和验证数据。例如,在这种情况下,用户可能更方便地提供一个字符串而不是初始化一个新的 uri 对象,因此 setter 允许使用任一类型的参数。我正在使用Object.assign 快​​速用用户提供的值覆盖任何默认值。

配置选项是只读的,因此 setter 是私有的:它应该只使用一次来初始化值。这从 typescript 4.3 开始工作,它允许 getter 和 setter 的不同可见性。

问题:

现在问题出在:Property '_uri' has no initializer and is not definitely assigned in the constructor. - 我收到此错误是因为 typescript 无法判断接口保证 uri 使用 Object.assign 在构造函数中初始化

我尝试通过在构造函数中手动添加 this.uri = config.uri 来解决此问题,但这也不起作用,因为我出于某种原因收到以下错误:Type 'string | Uri' is not assignable to type 'Uri'.

问题:

简而言之,如何使用 setter 在 typescript 中初始化只读/私有值?或者如果这不可能,我应该为我的配置结构使用哪种替代方法?

可能的解决方案:

我想我可以将 setter 代码直接集成到构造函数中,但由于以下原因,这种方法似乎远非理想:

  1. 如果您有很多跨多个 setter 的代码,构造函数会很快变得混乱。
  2. 这不适用于Object.assign,迫使您手动设置每个配置选项,这将非常冗长乏味。

【问题讨论】:

    标签: typescript constructor setter readonly


    【解决方案1】:

    我收到错误 '_uri' has no initializer and is not definitely assigned in the constructor.,因为 typescript 无法判断接口保证 uri 使用 Object.assign 在构造函数中初始化

    在这种情况下,您可以通过编写来抑制错误

    private _uri!: URL
    //          ^
    

    在你的class.

    也就是说,我建议不要为此使用 setter/getter,而是编写一个方法 private static validUri(uri: Uri | string): Uri 并在构造函数中像 this.uri = BaseUriConfiguration.validUri(config.uri); 一样使用它。

    【讨论】:

    • 感谢您的回答。我选择了静态方法:有时最简单的方法效果最好。我太专注于让 setter 工作,以至于忽略了一个明显的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多