【发布时间】: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 代码直接集成到构造函数中,但由于以下原因,这种方法似乎远非理想:
- 如果您有很多跨多个 setter 的代码,构造函数会很快变得混乱。
- 这不适用于
Object.assign,迫使您手动设置每个配置选项,这将非常冗长乏味。
【问题讨论】:
标签: typescript constructor setter readonly