简体   繁体   中英

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM