从只读类属性推断出的类型

时间:2018-07-10 11:17:30

标签: typescript typescript2.0

给出以下测试类:

class Test {
    private readonly testString = "hello";
    private readonly testStringImplicit: string = "hello";

    public constructor() {
        this.testString = "world";
        this.testStringImplicit = "world";
    }
}

当前,打字稿 2.8.2 (甚至是当前的2.9.2)为第一个属性testString产生以下错误:

TS2322: Type "world" is not assignable to type "hello".

我的问题:这是一个错误吗?

我想不是,但我不明白,为什么readonly属性的 type 可以是它们的值。

感谢您提供的所有有用答案

1 个答案:

答案 0 :(得分:5)

这有点令人困惑,但是您的testString的类型不是string,而是"hello"string literal type和字符序列hello。您的testStringImplicit被显式键入string,因此您可以为其分配任何字符串,但是您的testString只允许具有一个字符串文字值。

之所以具有该类型,是因为它是readonly,这是您用来初始化它的字符串。如果不是readonly,则推断的类型将为string,但是由于它是readonly,因此tsc假设初始化是您要编写的唯一位置,因此为"hello"提供了“最佳通用类型”,它是字符串文字类型。

正如jcalz指出的那样,这是intended behavior。该链接的相关要点:

  
      
  • const变量或readonly属性中推断出的,没有类型注释的类型是初始化器 as 的类型。
  •   

  
      
  • 使用初始化器为let变量,var变量,参数或非readonly属性推断出的类型,并且没有类型注释的是初始化器的扩展文字类型。 / li>   

该拉取请求的文本中未出现“构造函数”一词,因此,即使{{被允许,您也无法为构造函数中的testString分配不同的值1}}的规则,似乎没有在这里讨论。可能会在其他地方讨论。