【发布时间】:2020-09-28 15:05:15
【问题描述】:
在下面的例子中,我试图描述一个复杂的打字稿类型,我想在以后使用FinalType。问题是,由于它的复杂性,这种类型需要声明污染页面 IntermediaryType/IntermediaryType2 的中间类型。
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?
我看到您可以使用 方括号 将部分代码括起来,例如:
{
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。我尝试过使用return 或export,但都不起作用。
理想的情况是这样的:
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: () => {},
});
有什么线索吗?
使用@Aluan Haddad 的答案,目前我能做到的最好的是:
namespace _ {
type IntermediaryType = {
decisiveKey: true,
mutatedKey: (params: any) => void,
} | {
decisiveKey: false,
mutatedKey?: false,
}
interface IntermediaryType2 {
foo?: string,
bar?: boolean,
}
export type FinalType = IntermediaryType & IntermediaryType2;
}; type FinalType = _.FinalType;
const Foo = (param: FinalType) => {}
Foo({
decisiveKey: true,
mutatedKey: () => {},
});
我很想在上面添加一些语法糖!
【问题讨论】:
-
我认为你应该通过不同的文件来组织你的架构,在这种情况下,只导出 FinalType。通过这种方式,您将拥有一个包含所有中间类型和最终类型的文件,但是,只有最终类型可以在外部文件中使用。
-
这是一个在 90% 的情况下都很好的架构建议。但是当您键入使用稍微修改的现有类型的私有方法时;我几乎看不到放入外部文件的价值。
标签: javascript typescript typescript-typings encapsulation