'TypeScript complaining when trying to use a function as .replace argument
I have an array of objects for a replace function, which is inside a forEach loop (I did this so I wouldn't have to write .replace again and again). The replacement can either be a string or a function:
const content = `'Example'
"Another example
"Another example"`
const regexes = [{
}, {
name: 'apostrophe',
pattern: /(?<=\w)\'(?=\w)|(?<=\w)\'(?!\w)/g,
replacement: '’'
}, {
name: 'doubleQuotes',
pattern: /"([^"\n\r]*)("|$)/gm,
replacement: (x: any,y: any,z: any) => z === '"' ? `“${y}”` : `“${y}`
}]
regexes.forEach(regex => {
content = content.replace(regex.pattern, regex.replacement)
})
TypeScript (inside VS Code) is throwing this type error:
Argument of type 'string | ((x: any, y: any, z: any) => string)' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'.
Type 'string' is not assignable to type '(substring: string, ...args: any[]) => string'.ts(2769)
I think TypeScript is complaining that one of the replacement is a function?
What should I change in the code to remove this type error?
Here's there live code (I fixed the issues raised by the answer below.)
Solution 1:[1]
first, remove the empty entry from regexes or handle the empty entry in the forEach. you also need to define content with a let instead of const, since you're modifying the value.
for the apostrophe replacement, try using () => '’' instead of just a string. that will align the types of your replacement field, making them all functions and the compiler will be happy.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mizerlou |

