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
Readonlyfunction on runtime?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With