2

The following doesn't seem to compile:

declare namespace ns {
    interface Test {
        readonly x: number;
    }
}

with:

Cannot find name 'readonly'.
Property or signature expected.

nor does this:

declare namespace ns {
    interface Test {
        const x: number;
    }
}

with:

Property or signature expected.

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136

2 Answers2

3

Your example is compiled without error by TypeScript 2.0:

declare namespace ns {
    interface Test {
        readonly x: number;
    }
}

The current release is 1.8. In order to test with the next version, on a local installation: 1/ install the nightly build of TypeScript with npm install typescript@next, then 2/ execute the compiler: ./node_modules/.bin/tsc your-file.ts.

Paleo
  • 21,831
  • 4
  • 65
  • 76
1

You can't assign a value to a property in an interface in TypeScript. So how would you set a readonly variable if you are not allowed to initially set it.

You can take a look at the answer to this question here how you could solve this using a module instead:

module MyModule {
    export const myReadOnlyProperty = 1;
}

MyModule.myReadOnlyProperty= '2'; // Throws an error.

Update

It seems you have to wait for TypeScript 2.0 for this, which will have readonly properties then:

https://github.com/Microsoft/TypeScript/pull/6532

Community
  • 1
  • 1
malifa
  • 8,025
  • 2
  • 42
  • 57
  • 3
    _You can't assign a value to a property in an interface in TypeScript._ True, but I can assign a value to the property of an object that implements the interface, and in this case I want to prevent that. _So how would you set a readonly variable..._, this is for an ambient declaration, which means I am not setting the property's value; that is being done by the library. – Zev Spitz Jun 28 '16 at 09:35
  • @ZevSpitz true, sorry i kinda responded to fast without thinking enough ;) This seems to be a similar question, but the answer won't help you out much i guess: http://stackoverflow.com/questions/14796751/how-can-i-add-a-readonly-attribute-to-a-declarations-file – malifa Jun 28 '16 at 10:22