Search code examples
typescriptreadonly-attribute

Typescript readonly property assignment error but still compiling


I'm playing around with typescript atm and ran into a problem with readonly parameters. I set up an interface with readonly parameters but can still modify them on the initialized and imported object before compile time. The compiler complains about it but still compiles the code.

Here's my example:

Configuration.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;

Now i import it into my 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 tells me that config.port = 8080 is not allowed, also the compiler say's it:

[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.

But the server still starts on port 8080. So although the compiler throws an error it still compiles the code. I would expect an error to fail compilation as that is why i would want to use typescript, no?

Am I missing something, doing something wrong?


Solution

  • By default, the compiler will still output JavaScript even if there have been type errors. You can turn this off by setting the noEmitOnError compiler option to true:

    tsconfig.json:

    {
      "compilerOptions": {
        "noEmitOnError": true
      }
    }