TypeScript - 无法从 class' 对象定义中看到接口

TypeScript - can not see interface from class' object defition

我遇到了一个奇怪的问题:

interface PreferencesData {

}  
class Background {        
    a:PreferencesData;         // OK
    private state = {
        preferences : PreferencesData   // NOT OK
    }
..

当 "NOT_OK" - 它只是看不到 PreferencesData 并且拒绝编译。

但是对于 "a" 它是可见的并且没有抱怨。

我错过了什么吗?

更新: 如果我将 interface 更改为 class,那么它是可见的

您需要将类型信息放在对象的之前类型注释中,如下所示:

class Example1 {        
    a:PreferencesData;
    private state: { preferences: PreferencesData } = {
        preferences: ""
    }
}

为什么?因为对象字面量中的 : 分隔 key/value 对,所以右边的表达式应该是值,而不是类型注释。

这看起来确实很乱,因此您可以决定为您拥有的状态对象创建一个接口:

interface State {
    preferences: PreferencesData;
}

class Example2 {        
    a:PreferencesData;
    private state: State = {
        preferences: ""
    }
}

注意:上面的 "" 空字符串需要替换为有效的 PreferencesData 兼容结构 - 但原始问题没有具体说明那是什么。