Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
TypeScript: make field public only for special classes

Here's a problem. I work with pattern MVVM, which means I have some Views with display logic only and some ViewModels with functional logic only. ViewModels has methods and fields. And these fields and methods can be read or called by other ViewModel or by the View of ViewModel.

And I'd like to know, is there a way to make some fields visible only in View, but hidden (private) in other ViewModels?

I need something like this:

class ViewModel1 {
  doSomething = () => {...}; // can be called anywhere

  publicForView doSomethingInView = () => {...}; // can be called only in the View

  private doSomethingInViewModel = () => {...}; // can be called only here
}

// view is a HOC-function, which joins ViewModel with View
const View1 = view(ViewModel1, ({ viewModel }) => {
  viewModel.doSomethingInView(); // can be called
  viewModel.doSomething(); // can be called
  viewModel.doSomethingInViewModel(); // can't be called

  return <div/>;
});

class ViewModel2 {
  private viewModel1: ViewModel1;

  constructor() {
    viewModel.doSomethingInView(); // can't be called
    viewModel.doSomething(); // can be called
    viewModel.doSomethingInViewModel(); // can't be called
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you want a class in Typescript to expose only certain parts of a class you can create interfaces, so save on duplicate code using Pick / Omit will help in creating the interfaces.

eg..

class ViewModel {
  doSomething = () => {};  
  doSomethingInView = () => {}
  doSomethingInViewModel = () => {}
}

type View = Omit<ViewModel, 'doSomethingInViewModel'>
type Model = Omit<ViewModel, 'doSomethingInView'>

function doSomethingWithView(view: View) {
    view.doSomething();
    view.doSomethingInView();
    //view.doSomethingInViewModel();  will error
}

function doSomethingWidthModel(model: Model) {
    model.doSomething();
    model.doSomethingInViewModel();
    // view.doSomethingInView(); will error
}

const view = new ViewModel();
//we can pass view to both functions, but the methods will be restricted
doSomethingWithView(view);
doSomethingWidthModel(view);

Working example here -> TS Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!