I have a working solution to - export types defined from declaration file, that can be used within my project and to be exported out to external projects.
The only way I could make this work was using a namespace to wrap the type.
github - Project X
@types/index.d.ts
declare namespace projectGlobal {
interface Person = {
name: string;
age: number;
}
}
// other localised types here, cannot be exported...
interface Local {
func: () => string
}
src/index.ts
export type Person = ProjectGlobal.Person; // can only export if referenced via namespace.
// export type Local = Local; // This fails to export
const person1: Person = {
name: 'john',
age: 45
}
github Project Y
import {Person} from 'projectx';
const person1: Person = {
name: 'john',
age: 45
}
While I'm happy to settle for this as a solution I want to know if this is the right way to do this or if there is a best practice for this.
Declaration files are not supposed to be used like that. Usually you don't write them at all, actually. The main reasons when you want to write them are:
When you have a library in JavaScript and you want TypeScript users to be able to use it as well. You could rewrite your library in TypeScript, but this is not fun, so you can just write declarations and leave the code in JavaScript.
Sometimes if you want to declare some global things. Like for example, in React projects you can import data from image files
.png
,.jpg
and co. So React creates a.d.ts
file with declarations for them (because by default TS doesn't consider these files to be modules):That's pretty much it, in other cases just use normal
.ts
files:I don't see any reason, why you can't do that, if you have one, feel free to comment. If you just want separation between types and logic, create
types.ts
anddo-stuff.ts
and just useindex.ts
to reexport stuff: