I am using typescript with yarn for a private project, where I developed a package that is intended to be consumed by one or more other applications.
While starting on the consumer application, I ran into the following issue:
One of my const object exports is available as a type, but can not be resolved to its value. When trying to access the value in code, the consumer does not compile anymore. Const string literals however are accessible and everything works fine inside of the package itself.
Additional information:
- typescript: ^5.3.3
- tsup: ^8.0.2 for package compilation
- Using yarn link to provide the package to the consumer locally
- The object and the type share the same name. From what I found during my research this is acceptable, since types and values live in different spaces
Minimal (non-)working example:
Package:
/* ./types/constants.ts */
export const On = "on";
export const Off = "off";
export const PlayState = {
Play: "play",
Pause: "pause",
Stop: "stop",
} as const;
export type OnOff = typeof On | typeof Off;
export type PlayState = (typeof PlayState)[keyof typeof PlayState];
/* ./index.ts */
import * as Constants from "./types/constants.js";
const a: Constants.PlayState = Constants.PlayState.Play; // works as expected and compiles
export * as Constants from "./types/constants.js";
Consumer:
/* ./index.ts */
import { Constants } from "@author/pkg";
const a: Constants.OnOff = Constants.On; // works fine
const b: Constants.PlayState = "play"; // works fine
// const c: Constants.PlayState = Constants.PlayState.Play;
// shows error: "Property 'PlayState' does not exist on type 'typeof constants'"
I expected the imported package to work the same as it does in itself, given the information I found online suggests, that this is working. The compiled code looks fine to me, the PlayState export and declaration are present, but maybe I am missing something.
Any help is appreciated!
Instead of using export * as Constants, consider explicitly exporting and importing each constant. This can sometimes resolve issues where TypeScript might not correctly infer types or values due to the way modules are structured or bundled:
Hope that helps