I have generated (from GraphQL Codegen and my API) a TypeScript types modules file and want to add all of its types to my project, application-wide (globally). The types are in src/generated/generatedTypes.ts which also has an export {}; line (making it a module).
tsconfig.ts defines:
"include": [
"src/generated", // bring in my generated types
"**/*.ts", // bring in the rest of the project's files
The first include directive tells TypeScript to load all the types from my src/generated folder (including generatedTypes.ts). However, inside my .ts files I still get "Cannot find name SomeType" errors; the types aren't there. How can I make the types in generatedTypes.ts available to the rest of my project?
Full tsconfig.ts file:
{
"ts-node": {
"require": ["tsconfig-paths/register"]
},
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"baseUrl": "./",
"checkJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"paths": {
"app/*": ["./app/*"],
"pages/*": ["./pages/*"],
"src/*": ["./src/*"]
},
"plugins": [
{ "name": "next" }
],
"strictNullChecks": true,
"target": "es2017",
// "types": ["node"],
// "typeRoots": ["./node_modules/@types", "./src/generated"]
},
"include": [
"src/generated",
"next-env.d.ts",
".next/types/**/*.ts",
"**/*.d.ts",
"**/*.ts",
"**/*.tsx",
"**/*.js",
"postgraphile.cjs",
],
"exclude": ["node_modules", "migrations/**"],
"skipLibCheck": false,
// "skipLibCheck": true /* Skip type checking all .d.ts files. */
}
The types in generatedTypes.ts aren't important but the file looks like:
export {};
type System = GQLNode & {
__typename?: 'System';
createdAt?: Maybe<Scalars['Datetime']['output']>;
// lots more definition
};
// lots more types
There is no global declaration in the file because I didn't think it was necessary. The end of the file is just:
type SignupMutation = {
__typename?: 'Mutation';
registerUser?: {
__typename?: 'RegisterUserPayload';
jwtToken?: any | null;
} | null;
};
With help (from @Eric MORAND in the comments; now deleted, but thank you!), I found the problem: my types weren't wrapped in a global declaration.
With GraphQL Codegen you need to add noExport: true under the generates config in the codgen.ts or codgen.yaml file to have it add the relevant wrapper:
declare global {
// file contents
}