【问题标题】:TypeScript: make field public only for special classesTypeScript:仅对特殊类公开字段
【发布时间】:2021-12-16 04:26:21
【问题描述】:

这是一个问题。我使用模式MVVM,这意味着我有一些仅具有显示逻辑的视图 和一些仅具有功能逻辑的ViewModelsViewModels 有方法和字段。并且这些字段和方法可以被其他ViewModel或者ViewModelView读取或调用。

我想知道,有没有办法让某些字段仅在 View 中可见,但在其他 ViewModels 中隐藏(私有)?

我需要这样的东西:

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
  }
}

【问题讨论】:

  • 我会创建两个界面,一个用于视图,一个用于模型。然后让 ViewModel 实现它们。然后只需使用每个特定的接口。
  • 嗯,看起来是一个工作变体。但在这种情况下,我必须编写很多重复的代码。如果我理解你,我需要为每个 ViewModel 提供 2 个接口和 1 个类。在这种情况下,我的代码库量增加了 4000-5000 行代码
  • 并非如此,这取决于您如何创建接口。使用 Pick / Omit 会使事情变得更短。我看看能不能举个简单的例子。

标签: javascript reactjs typescript oop mvvm


【解决方案1】:

如果您希望 Typescript 中的类仅公开类的某些部分,您可以创建接口,因此使用 Pick / Omit 节省重复代码将有助于创建接口。

例如..

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);

这里的工作示例 -> TS Playground

【讨论】:

  • 但我仍然必须复制这些 doSomethingInViewModeldoSomethingInView。而且在有更多这样的字段的情况下,这样的代码看起来会很脏。也许我可以在课堂上标记我想禁用的字段?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2015-09-13
  • 2018-04-11
  • 1970-01-01
相关资源
最近更新 更多