Skip to content

Instantly share code, notes, and snippets.

@drothmaler
Last active May 6, 2020 07:26
Show Gist options
  • Select an option

  • Save drothmaler/2557fc16b55dcae6aec6f4baf98d235d to your computer and use it in GitHub Desktop.

Select an option

Save drothmaler/2557fc16b55dcae6aec6f4baf98d235d to your computer and use it in GitHub Desktop.
interface Foo {
n: number
s: string
}
class Bar1 {
n: number
s: string
foo: Foo
} // anything can be changed
let bar1 = new Bar1()
bar1.n = 42 // <-- Working
bar1.s = "foo" // <-- Working
bar1.s.length = 0 // <-- Error (string is always immutable)
bar1.foo = { // <-- Working
n: 21,
s: "bar"
}
bar1.foo.n = 42 // <-- Working
bar1.foo.s = "foo" // <-- Working
class Bar2 {
readonly n: number
readonly s: string
readonly foo: Foo
} // properties of Bar2 can't be reassigned
let bar2 = new Bar2()
bar2.n = 42 // <-- Error
bar2.s = "foo" // <-- Error
bar2.s.length = 0 // <-- Error
bar2.foo = { // <-- Error
n: 21,
s: "bar"
}
bar2.foo.n = 42 // <-- Working
bar2.foo.s = "foo" // <-- Working
class Bar3 {
n: Readonly<number> // has no effect
s: Readonly<string> // has no effect
foo: Readonly<Foo>
} // properties of Foo can't be reassigned
let bar3 = new Bar3()
bar3.n = 42 // <-- Working
bar3.s = "foo" // <-- Working
bar3.s.length = 0 // <-- Error
bar3.foo = { // <-- Working
n: 21,
s: "bar"
}
bar3.foo.n = 42 // <-- Error
bar3.foo.s = "foo" // <-- Error
class Bar4 {
readonly n: number
readonly s: string
readonly foo: Readonly<Foo>
} // Neither properties of Foo, nor Bar4 can't be reassigned
let bar4 = new Bar4()
bar4.n = 42 // <-- Error
bar4.s = "foo" // <-- Error
bar4.s.length = 0 // <-- Error
bar4.foo = { // <-- Error
n: 21,
s: "bar"
}
bar4.foo.n = 42 // <-- Error
bar4.foo.s = "foo" // <-- Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment