Issue
I want to add a property to the process
object in React, so Webpack
will replace it with the DefinePlugin
plugin:
declare global {
interface Process {
gitInfo: {
GIT_COMMIT_DATE?: string;
GIT_COMMIT_HASH?: string;
GIT_BRANCH?: string;
GIT_COMMIT_MESSAGE?: string;
};
}
}
const gitInfo = process.gitInfo; // Error: Property 'gitInfo' does not exist on type 'Process'.ts(2339)
What is the problem?
Solution
The type you are augmenting is qualified by the global NodeJS
namespace. Therefore you need to write it as
declare global {
namespace NodeJS {
interface Process {
gitInfo: {
GIT_COMMIT_DATE?: string;
GIT_COMMIT_HASH?: string;
GIT_BRANCH?: string;
GIT_COMMIT_MESSAGE?: string;
}
}
}
}
Remarks
After some discussion in comments, it became clear that the OP was attempting to avoid namespaces due to an eslint TypeScript rule. While linters are most definitely helpful, and it is indeed good practice to avoid arbitrary nesting, it's important to understand why a rule is in place and what limitations it imposes. In other words, even when you obey the linter it's desirable understand the rational for the rule. In this case, we must disable the rule because, as we are augmenting an interface
scoped to a namespace
and definitions can only be augmented when the augmentation is within the exact same scope - different scopes never colllide.
Basically, the lint rule that you were following inherently precludes your ability to accomplish a very reasonable and common goal - to augment a declaration provided by a library which uses the namespace
construct to aggregate types thus not polluting the set of globally declared types.
Answered By - Aluan Haddad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.