I would love to destructor onto class fields. For example:
function foo() {
return [1, 2]
}
class MyClass {
;[one, two] = foo()
}
const o = new MyClass()
o.one // 1
o.two // 2
And similar with object destructuring.
This could go well with constructor args available in fields: Proposal: access to constructor parameters in field initializers
Real-world use case:
Solid.js, for example, provides a createSignal
function that returns a tuple:
- a function for reading a value (a "getter")
- a function for setting a value (a "setter")
const [foo, setFoo] = createSignal(0)
// increment the value every second:
setInterval(() => setFoo(foo() + 1))
// log the value every second:
createEffect(() => console.log(foo()))
With destructuring we could easily do this:
class MyClass {
;[foo, setFoo] = createSignal(0)
}
const o = new MyClass
o.foo() // read
o.setFoo(123) // write
This is expecially nice in lieu of decorators which will allow us to make reactive properties easily. Plus some people prefer less magic, and assigning a getter and setter from createSignal
to two properties is less to explain than a decorator may be.
Plus not everything is about reactivity, there might just be something that returns a tuple of distince things, or an object:
class MyClass {
;{value, abort, interval} = someProcess() // syntax?
}