Looking to implement custom global declaration in NextJS
In my NextJS project, I've defined a global prototype for String as shown below
utils.d.ts
export {}
declare global {
interface String {
/**
* Returns string after removing all html tags.
*/
stripHtml(): string
}
}
String.prototype.stripHtml = function (): string {
return this.replace(/(<([^>]+)>)/gi, '')
}
Then I've added utils.d.ts file to tsconfig.json like so
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": ["./*"]
},
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"include": ["utils.d.ts", "next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Next, I've utilized it within my component Example.tsx like below
Example.tsx
import React from 'react'
interface Props {
posts: Record<string, any>[]
}
const Example: React.FC<Props> = ({ posts }) => {
return (
<section>
<div className="container">
<div>
{posts.map((item, idx) => {
const post = item.attributes
const { title, content } = post
return (
<div key={`post-${idx}`}>
<div>
<h2>{title}</h2>
<p>{content.stripHtml()}</p>
</div>
</div>
)
})}
</div>
</div>
</section>
)
}
export default Example
Now the VS Code no longer shows errors related to the declaration. However, when I run the project using the dev command, I encounter the following error.
TypeError: content.stripHtml is not a function
at eval (webpack-internal:///./components/Example.tsx:37:58)
...
(additional error messages)