Search code examples
typescripttypesconstantsconstraints

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

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