Assume that I'm coding a library in javascript, with typescript declaration files, and I want to create the "shape" of the library instance via interface, like that:
export interface Library {
foo: string;
bar: string;
}
Now assume that foo
and bar
type would be more complex and I want to carry it out to distinct type alias like:
export type ID = string | number;
export interface Library {
foo: ID;
bar: ID;
}
Now I want to give some sense to ID
(cause the "id" doesn't tell a thing), and the only way I think I can do this is to move it to distinct namespace, which is essensially should be named as library - "Library":
export namespace Library {
export type ID = string | number;
}
export interface Library {
foo: Library.ID;
bar: Library.ID;
}
Though it works, it's confusing and ambiguous because one import would be two different things at same time
How do I solve this? Maybe some naming tip?
There's nothing wrong with this:
export type ID = string | number;
export interface Library {
foo: ID;
bar: ID;
}
Remember that everything from your library must be explicitly imported from your library to be used. And when you do that, you can rename the imports if that matters to the code that is doing the importing.
import { Library, ID as LibraryID } from 'library'
// Locally defined ID that is different somehow
interface ID = { _id: number, cacheKey: string } // or whatever
const localId: ID = { _id: 123, cacheKey: 'qwerty' }
const libId: LibraryID = 123
And in most typescript code editors you can cmd/ctrl click on a type to jump to that definition. This would jump to your library and it would be pretty clear where the type comes from.
Most high profile libraries don't hide their types away in any namespace. For example:
import { Reducer } from 'react'
React doesn't care if you have other types named Reducer
. But if you do, you could easily change its local name in your own file as described above.
TL;DR: I think you're trying to solve a problem that doesn't really exist.