Zev Spitz
Zev Spitz

Reputation: 15297

How can I declare a readonly property in a declarations file?

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.

Upvotes: 2

Views: 2596

Answers (2)

Paleo
Paleo

Reputation: 23682

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.

Upvotes: 3

malifa
malifa

Reputation: 8165

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

Upvotes: 1

Related Questions