Defining a type file for external data
I'm bringing in data from a Firebase firestore into an app which is partway through a js -> ts conversion. I've gone through and created types for the entire firestore structure, and would like to have a single import like:
import "@companyname/types";
I've got everything gathered up in namespaces under a root namespace, all defined within a .d.ts file, so I can closely mimic the data store's structure, e.g.
cr.users.user.manifest.Package
And it seems like it'll work pretty well, besides being verbose.
However, I'm running into several issues:
-
without a corresponding
.tsfile, Typescript complains. But since there's nothing to define in the.tsfile, as I'm typing external data, all I have is anexport {}statement to get the compiler off my back. -
importing the type definitions is spotty at best. Sometimes it works in the editor exactly as intended, however when I try to compile, the compiler can't find the definitions.
Here's the rough shape of what I'm currently doing:
declare namespace cr {
let Users: cr.users.Users;
}
declare namespace cr.users {
interface Users {
[FirebaseKey: string]: User
}
let User: User;
interface User {
manifest: cr.users.user.Manifest;
}
}
declare namespace cr.users.user {
let Manifest: Manifest;
interface Manifest {
...
}
}
I've also tried various combinations of exporting, but this seems to work the best...until I try to compile.
Is it possible to define a type file in this way, as a collection of types meant to be used explicitly, rather than a description of an interface?
Posted Sep 17, 2019, 5:39 AM UTC
What is the actual error output by the compiler? Your description makes it sound like
tscis not including your.d.tsfile int the compilation. What is the output when you runtsc --listFiles? Is your.d.tsfile included?I also find it odd that you are declaring variables in you namespace:
let User: User;. Are you sure that is necessary? Do you have a javascript file providing the implementation of that variable?error TS2503: Cannot find namespace 'pr'And if I remove the
index.tsfile:If I copy and paste the entire type file into whatever I'm working in, it works fine, but naturally that's a less than ideal solution.
If I run
tsc --listFiles, theindex.tsfile that I made to satisfy the modules requirement is shown, but not the.d.tsfile.As for why I'm using
let, that's because an interface declared within a namespace wouldn't actually show up in editor's available options unless I defined them as properties of the namespace.All in all, this doesn't seem like the right way to go about doing what I'm trying to do.
How would you organize a collection of types and make them easily importable?
Edit: I appear to have this working, though I'm still not sure if it was the best way to go about it:
And edited the
jest.configfile to include:"moduleFileExtensions": ["js", "json", "jsx", "ts", "d.ts", "tsx", "node"]