Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to declare type as constant?

I will have several objects with the same property names, e.g.

const a = {foo: 111,};
const b = {foo: 222,};

So I’d like to have a global type for them, e.g.

type T = {foo: number,};
// in another file
const a: T = {foo: 123,};

But those objects are supposed to be constant, i.e. their values should not change since the time of their declaration. Is it possible to enforce such thing? So that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let a: T = {foo: 123,};
// or 
const a = {foo: 123,};
a.foo = 321;

would throw an error.

Is it possible? Something like this:

//this is a syntax error
type T = {foo: number,} as const;

Thank you.

>Solution :

Use the readonly property modifier:

type T = { readonly foo: number };
//         ~~~~~~~~
const a: T = { foo: 123 };

a.foo = 321; // error on a.foo

If you have multiple properties, you can use the Readonly utility type:

type T = Readonly<{ foo: number }>;
//       ~~~~~~~~
const a: T = { foo: 123 };

a.foo = 321; // error on a.foo

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading