我来自TypeScript的世界,所以我有点困惑为什么下面这些不会失败。
class Bar {
foo: string
}
let bar = new Bar();
let test = bar.foo;
test = 4; // all is good here, while it should fail!
发布于 2018-01-21 15:44:26
它被称为类属性语法https://flow.org/en/docs/types/classes/
在您的示例中
class Bar {
foo: string // not defined
}
let bar = new Bar()
let test = bar.foo // Copy value not type, should use let test: string = bar.foo
test = 4发布于 2018-02-18 00:57:55
您的代码不会失败,因为您实际上已经将变量test定义为any。赋值时,类型不会在变量之间传递。
如果你想强制变量test作为string类型,你应该定义它的类型。
let test: string = bar.foo; // ok
test = 4; // flow error这将抛出以下错误
^ Cannot assign `4` to `test` because number [1] is incompatible with string [2].https://stackoverflow.com/questions/48364503
复制相似问题