从只读推断的类型 class 属性
Type inferred from readonly class property
给出的是以下测试class:
class Test {
private readonly testString = "hello";
private readonly testStringImplicit: string = "hello";
public constructor() {
this.testString = "world";
this.testStringImplicit = "world";
}
}
目前,Typescript 2.8.2(甚至是当前的 2.9.2)为第一个 属性 testString
产生以下错误:
TS2322: Type "world" is not assignable to type "hello".
我的问题:这是一个错误吗?
我猜不是,但我不明白,为什么只读属性的类型可以是它们的值
感谢您的每一个有用的回答
有点乱,你的testString
的类型不是string
,是"hello"
,string literal type的字符序列是[=13] =]、e
、l
、l
、o
。您的 testStringImplicit
是明确键入的 string
,因此您可以为其分配任何字符串,但您的 testString
只允许具有该字符串文字值。
它具有该类型,因为它是 readonly
,这就是您用来初始化它的字符串。如果它不是 readonly
,推断的类型将是 string
,但因为它是 readonly
,所以 tsc
假设初始化是您要写的唯一地方给它,所以给它 "best common type" for "hello"
,这是字符串文字类型。
如jcalz helpfully points out, this is intended behavior。 link 中的相关要点:
- The type inferred for a
const
variable or readonly
property without a type annotation is the type of the initializer as-is.
而
- The type inferred for a
let
variable, var
variable, parameter, or non-readonly
property with an initializer and no type annotation is the widened literal type of the initializer.
"constructor" 这个词没有出现在那个 pull request 的文本中,所以你不能在构造函数中为 testString
分配不同的值,即使你被允许按照 readonly
的规则,那里似乎没有讨论。可能会在别处讨论。
给出的是以下测试class:
class Test {
private readonly testString = "hello";
private readonly testStringImplicit: string = "hello";
public constructor() {
this.testString = "world";
this.testStringImplicit = "world";
}
}
目前,Typescript 2.8.2(甚至是当前的 2.9.2)为第一个 属性 testString
产生以下错误:
TS2322: Type "world" is not assignable to type "hello".
我的问题:这是一个错误吗?
我猜不是,但我不明白,为什么只读属性的类型可以是它们的值
感谢您的每一个有用的回答
有点乱,你的testString
的类型不是string
,是"hello"
,string literal type的字符序列是[=13] =]、e
、l
、l
、o
。您的 testStringImplicit
是明确键入的 string
,因此您可以为其分配任何字符串,但您的 testString
只允许具有该字符串文字值。
它具有该类型,因为它是 readonly
,这就是您用来初始化它的字符串。如果它不是 readonly
,推断的类型将是 string
,但因为它是 readonly
,所以 tsc
假设初始化是您要写的唯一地方给它,所以给它 "best common type" for "hello"
,这是字符串文字类型。
如jcalz helpfully points out, this is intended behavior。 link 中的相关要点:
- The type inferred for a
const
variable orreadonly
property without a type annotation is the type of the initializer as-is.
而
- The type inferred for a
let
variable,var
variable, parameter, or non-readonly
property with an initializer and no type annotation is the widened literal type of the initializer.
"constructor" 这个词没有出现在那个 pull request 的文本中,所以你不能在构造函数中为 testString
分配不同的值,即使你被允许按照 readonly
的规则,那里似乎没有讨论。可能会在别处讨论。