3 ms·
class Person { readonly name: string; couldn't they have just reused `const`?
by leeoniya 10y ago
class Person {
readonly name: string;
couldn't they have just reused `const`?
- clappski 10y agoconst means a completely different thing depending on what language you come from (even JavaScript). I think readonly has a much clearer meaning.
- jameslk 10y agoFrom my understanding, const would mean the property would be immutable even within the class, where as readonly means it's only immutable when used from outside the class but still mutable inside the class.
- judah 10y ago> "where as readonly means it's only immutable when used from outside the class but still mutable inside the class" Small correction: The readonly modifier means you can initialize the variable, but can't mutate it (even within the same class). For example, you can initialize a readonly field inside a constructor, something you can't do with const. Some good docs on it here: https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html https://basarat.gitbooks.io/typescript/content/docs/types/re...
- jameslk 10y agoIt appears you're right: > Read-only properties may have initializers and may be assigned to in constructors within the same class declaration, but otherwise assignments to read-only properties are disallowed. Thanks for pointing that out.
- RyanCavanaugh 10y ago`const` applies to a binding; `readonly` applies to a property. The difference is important because you can alias a mutable property through a readonly reference (thus observing two different values from the same reference if someone with a mutable handle on the object changes it), whereas a const will always have the same value because it's an immutable reference to a particular value/object.
- leeoniya 10y agoah i guess immutable aliasing is useful. then it's more powerful than const and can replace it wholesale, bindings included.