#Accessing private/protected member internally in a type safe manner

1 messages · Page 1 of 1 (latest)

gray verge
#
class Foo {
  protected data = 'some data'
}

declare const fooFromConsumer: Foo

type InternalFoo = Foo & {
  data: Foo['data']
}

const internalFoo = fooFromConsumer as InternalFoo
internalFoo.data

I'm making a framework which provides a Foo class, which is meant to be extended by the consumer of my framework and they are allowed to modify data in some way. I want data to be protected so that it's not visible outside.
When consumer of my framework eventually passes an extended instance of Foo (fooFromConsumer) back to me, I would like to access data. The only way seems to be declaring an internal type (InternalFoo) then forcibly casting to it.
This works, however it is not entirely type safe, as if I rename Foo.data, it won't automatically rename InternalFoo.data.
Is there a better approach?

gray verge
#

Just found out that you can do fooFromConsumer['data'] and bypass private/protected 😅