What the other posters have added is true based on published materials, but does not line up with my lived experience. I can't speak to iMac models newer than 2013 and I would assume the restriction about post-2014 iMac models to be true.
But I have successfully used target display mode on a 2010 iMac with a 2019 MacBook Pro, a 2020 MacBook Pro, a 2022 MacBook Air, and a 2023 MackBook Pro. Also have run a 2019 MacBook Pro into a 2013 iMac. The iMac in every case was running High Sierra, but the MacBook Pros / Air were running whatever the latest version of MacOS was at the time.
So even though newer iMacs are not supported, sticking with 2009-2014 iMacs running High Sierra and below can still work with newer Macs, including M1 and M2 chip-based models.