0

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: '&rsquo;'
  }, {
    name: 'doubleQuotes',
    pattern: /"([^"\n\r]*)("|$)/gm,
    replacement: (x: any,y: any,z: any) =>  z === '"' ? `&ldquo;${y}&rdquo;` : `&ldquo;${y}`
}]

regexes.forEach(regex => {
  content = content.replace(regex.pattern, regex.replacement)
})

TypeScript (inside VS Code) is throwing this type error:

enter image description here

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.)

1

1 Answer 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 () => '&rsquo;' instead of just a string. that will align the types of your replacement field, making them all functions and the compiler will be happy.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I'm curious, is there a way of making this work without making the first replacement a function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.