When Jack Nicholson signed on to play Frank Costello, the top-dog gangster in “The Departed” — Martin Scorsese’s cat-and-mouse take on Boston’s Irish mob — his role had yet to be written.

The film is a remake of the 2002 Hong Kong crime pic “Infernal Affairs,” in which Nicholson’s role was not much beyond a brief cameo.

“I actually turned the movie down the first time it came to me,” says the 12-time Oscar-nominated Nicholson, “because the character didn’t really exist. But Leo (DiCaprio) and Marty talked me into it. I guess you can say I was attracted to the company.”

Together that highly talented group created a role that is pure Jack.

The film tells the story of two moles — DiCaprio plays a cop undercover in Nicholson’s underworld empire, while Matt Damon plays a lifelong mobster stashed inside Boston’s police force — bouncing between scenes of abject violence and slowly ratcheting don’t-get-caught tension with Nicholson as both puppeteer and object of the hunt.

The results are a kind of wildly creative, ever-increasing madness that keeps the throttle at full tilt.

“Marty is very free with his ideas,” says Nicholson, “and very receptive to yours. We built this character layer by layer, until we had something that fit inside a great genre film, but also pushed the envelope until the movie becomes almost operatic.”

And while the danger with any pic that’s aiming for over-the-top theatricality — especially with Nicholson onboard — is one of pure farce, the actor walks a mighty thin line, turning in a perf that Variety’s Todd McCarthy found “theatrical in an entertaining way” and the San Francisco Chronicle’s Mike LaSalle calls “a psychologically detailed portrait of a twisted, old murderer.”

What makes that portrait even better is the fact that many of the key elements were improvised.

“There’s a scene in a bar where I’m scaring the shit out of Leo’s character with a gun. There wasn’t any gun in the script. We had shot the scene the night before but Marty said he had a light schedule the next day and wanted to try a few more takes. I wanted to come up with something different, so I asked the prop master to hide a gun on the set, and to bring a fire extinguisher as well. The look on his face when I asked for that fire extinguisher was priceless.”

And, as in most Nicholson performances, the results speak for themselves.

Favorite film of the past five years: “Hustle and Flow” “There’s a lot in this movie that’s familiar from a certain approach, but unusual in the way that the story presented. It became a movie of raw, unmitigated power.”

Actor who impressed you greatly after working together: Ray Winstone. “I don’t know if I was more impressed by his performance or that he was leaving to go star in ‘Beowulf’ right after we wrapped, but he’s a powerhouse.”

Next project: “The Bucket List,” directed by Rob Reiner and co-starring Morgan Freeman.