打字稿打字封装

问题描述 投票:1回答:1

在下面的示例中,我试图描述一个复杂的打字稿类型,我想在以后使用FinalType。事实是,由于它的复杂性,该类型需要声明污染页面IntermediaryType / IntermediaryType2的中间类型。

Playground

type IntermediaryType = {
  decisiveKey: true,
  mutatedKey: (params: any) => void,
} | {
  decisiveKey: false,
  mutatedKey?: false,
}

interface IntermediaryType2 {
  foo?: string,
  bar?: boolean,
}

type FinalType = IntermediaryType & IntermediaryType2;

const Foo = (param: FinalType) => {}

Foo({
  decisiveKey: true,
  mutatedKey: () => {},
});

我的问题是,有没有办法使中介类型不可访问,并且仅允许使用FinalType


我已经看到您可以使用brackets

括住部分代码,如:
{
  type IntermediaryType = {
    decisiveKey: true,
    mutatedKey: (params: any) => void,
  } | {
    decisiveKey: false,
    mutatedKey?: false,
  }

  interface IntermediaryType2 {
    foo?: string,
    bar?: boolean,
  }

  type FinalType = IntermediaryType & IntermediaryType2;
}

const Foo = (param: FinalType) => {}

Foo({
  decisiveKey: true,
  mutatedKey: () => {},
});

但是显然我无法访问FinalType。我尝试使用returnexport,但均无效果。

理想情况是:

type FinalType = {
  type IntermediaryType = {
    decisiveKey: true,
    mutatedKey: (params: any) => void,
  } | {
    decisiveKey: false,
    mutatedKey?: false,
  }

  interface IntermediaryType2 {
    foo?: string,
    bar?: boolean,
  }

  return IntermediaryType & IntermediaryType2;
}

const Foo = (param: FinalType) => {}

Foo({
  decisiveKey: true,
  mutatedKey: () => {},
});

任何线索?

在下面的示例中,我试图描述一个复杂的打字稿类型,我想在以后的FinalType中使用它。事实是,由于其复杂性,这种类型需要声明中介...

javascript typescript typescript-typings encapsulation
1个回答
0
投票

您实际上要做什么,为类型引入任意范围,可以通过TypeScript

© www.soinside.com 2019 - 2024. All rights reserved.