在设置器中接受数组和非数组值-解决不同的访问器类型

时间:2019-03-04 15:19:45

标签: typescript

我的Angular组件具有一个通常在字符串数组上运行的输入:

@Input() names: string[]

<my-comp [names]="['Adam', 'Betty']"></my-comp>

但是我想提供一种替代语法,以便用户无需键入方括号即可提供一个值:

<my-comp names="Adam"></my-comp>

并在设置器中进行处理,如下所示:

private _names: string[];
@Input() set names(value: string[] | string) {
  this._names = Array.isArray(value) ? value : [value];
}
get names(): string[] {
  return this._names;
}

但是,这会引发TSLint错误TS2380,抱怨访问器应该具有相同的类型。

我的问题是:是否有解决这种情况的好的TS方法?

1 个答案:

答案 0 :(得分:1)

好吧,TypeScript将属性访问器视为不动产,并且对此非常严格。

最简单的方法就是给吸气剂/塞特剂赋予不同的名称,例如

let labelAppearance = UILabel.appearance()
if let textStyle = labelAppearance.font.fontDescriptor.object(forKey: UIFontDescriptor.AttributeName.textStyle) as? UIFont.TextStyle {
    // this would be the place to check for the TextStyle and use the corresponding font

    let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
    labelAppearance.font = fontMetrics.scaledFont(for: mayAwesomeBodyFont)
}

,或者在这种情况下,Angular允许将其映射到真实的输入名称

font

因此您甚至不需要私有财产。

相关问题