Reputation: 6590
I've come across a pattern that can be summarized as:
export namespace Foo {
export enum Bar {}
}
export type Foo = Omit<typeof Foo, 'Bar'>
(Original code here.) With my rudimentary understanding of typescript, what I think this is doing is:
Foo
typeof Foo
to create a type from that namespace.Bar
from the type created in 2, and aliasing this type to identifier Foo
.So far so good, I think, but please correct me if I'm wrong. At this point things get into magic territory for me. This is because when Foo
is imported from another file, somehow magically the namespace Foo
is imported, rather than the type alias Foo
. My questions are:
Foo
due to type inference magic or is there something else going on here that I should know?Foo
s, is it at all weird that we have two things with the same name without a name collision? Is the collision avoided by the fact that namespaces are objects and type aliases are types?Upvotes: 0
Views: 1300
Reputation: 8843
Your thinking is correct with regards to what the code is doing.
For example: https://github.com/rokoroku/react-redux-typescript-boilerplate/blob/master/src/app/components/TodoList/index.tsx#L10
Here, TodoActions
is used as a type, so the compiler knows that it refers to the exported type alias.
Another example: https://github.com/rokoroku/react-redux-typescript-boilerplate/blob/master/src/app/reducers/todos.ts#L16
Here, TodoActions.Type.ADD_TODO
is used to create a property, so the compiler, again, knows that it refers to the namespace.
You can actually see this if you hover over the identifier in VS Code:
The following article explains the exact question you have: https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
Upvotes: 1