Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly variable vs Readonly-Typed method in typescript

What is the difference between Readonly variable and Readonly-Typed Method in typescript?

Readonly Variable

length: Readonly<Number | number | String | string> = 1;

vs

Readonly-typed Method

length(lenght: Number | number | String | string): Readonly<Number | number | String | string> {
        var width: Readonly<Number | number | String | string> = lenght;
        return width;
    }
  • What are the difference's for those thinks?
  • And is it possible to assign value for Readonly function on runtime?
like image 418
Ramesh Rajendran Avatar asked Jul 25 '26 09:07

Ramesh Rajendran


1 Answers

Readonly<T> is an object-type mapping:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

It will make all properties of T appear read-only to the compiler - So it doesn't actually make sense to use it on either number or string to begin with, because neither have properties.

if you want a true read-only --but internally changeable-- property at run-time then use a getter.

interface IFoo {
  readonly length: number;
}

class Foo implements IFoo {
  private _length: number;

  get length(): number {
    return this._length;
  }

  change(length: number) {
    this._length = length;
  }
}

There is no difference between a variable typed Readonly<T> and a method that returns a variable typed Readonly<T> bar the extra step of using a method.

like image 188
Meirion Hughes Avatar answered Jul 27 '26 22:07

Meirion Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!