JSFiddle - React, Tailwind, and code Playground

by kontrach

TypeScript

// ways to create readonly objects

// 1) Object.freeze 
// but only for one level of nesting and primitives
const o = Object.freeze({ foo: 'bar' });

o.foo = 10 // error;

// 2) enum
// Pros: straightforward description
// Cons: can't be used with booleans and other values. Strings and numbers are OK.
enum o2 {
    foo = 'bar',
    notABoolean = false,
    notANumber = 2
}

o2.foo = 'dd';

// 3) Class
// but it's too verbose and shows properties from prototype of the constructor
class o3 {
    static readonly foo = 'bar'
    static readonly booolean = false
}

o3.foo = 10;

// [start] 4) Use Readonly type
// Cons: too verbose and doesn't have autocomplete feature
interface o4Interface extends Readonly<{ [key: string]: any }> { }
const o4: o4Interface = {
    foo: 'foo',
    boooolean: false
}
o4.foo = 10;

// to have autocomplete feature, you would need to define all properties
// but it's even more verbose than previous variant
interface o4aInterface {
    foo: string;
    booolean: boolean;
}
const o4a: Readonly<o4aInterface> = {
    foo: 'bar',
    booolean: true
}

o4a.foo = 'ddd';
// [end] 4) Use Readonly type

// 5) Object.defineProperty || Object.defineProperties
// Cons: doesn't have autocompletion and doesn't throw or lint problems
const o5 = Object.defineProperties({}, {
    foo: {
        value: 'foo',
        writable: false,
        configurable: false
    },
    booolean: {
        value: false,
        configurable: false,
        writable: false
    }
});

o5.foo = 10;
console.log(o5);