我正在玩 typescript atm 并遇到了只读参数的问题。我设置了一个带有只读参数的接口,但仍然可以在编译前在初始化和导入的对象上修改它们。编译器抱怨它,但仍然编译代码。
这是我的例子:
配置.ts
import { readFileSync } from 'fs'
import * as YAML from 'yaml'
/**
* @interface Configuration
* Defines the server configuration
*/
interface Configuration {
readonly port: number
}
let config: Configuration
let initialized: boolean = false
if (!initialized) {
const file = readFileSync(__dirname + '/../../config.yml', 'utf8')
config = YAML.parse(file)
initialized = true
}
export default config;
现在我将它导入我的index.ts
:
import app from './App'
import config from './internals/Configuration' //config.port is now 8889
// This is not allowed.
config.port = 8080
app.listen(config.port, (err) => {
if (err) {
return console.log(err)
}
return console.log(`server is listening on ${config.port}`)
})
IDE告诉我这config.port = 8080
是不允许的,编译器也这么说:
[08:49:02] File change detected. Starting incremental compilation...
src/index.ts:4:8 - error TS2540: Cannot assign to 'port' because it is a read-only property.
4 config.port = 8080
~~~~
[08:49:02] Found 1 error. Watching for file changes.
但是服务器仍然在端口 8080 上启动。所以尽管编译器抛出了一个error
它仍然编译代码。我希望error
编译失败,因为这就是我想使用打字稿的原因,不是吗?
我错过了什么,做错了什么吗?