diff --git a/compiler/typecheck/TcHsSyn.hs b/compiler/typecheck/TcHsSyn.hs
index b3f9a691176f730ef395bc72773e0dbbb24a1dac..986047bdedfd1851d6f3be04cd290ad6468170e4 100644
--- a/compiler/typecheck/TcHsSyn.hs
+++ b/compiler/typecheck/TcHsSyn.hs
@@ -1673,7 +1673,9 @@ zonkCoHole env hole@(CoercionHole { ch_ref = ref, ch_co_var = cv })
                                    , text "Type-correct unfilled coercion hole"
                                      <+> ppr hole )
                          ; cv' <- zonkCoVar cv
-                         ; return $ mkHoleCo (hole { ch_co_var = cv' }) } }
+                         ; return $ mkCoVarCo cv' } }
+                             -- This will be an out-of-scope variable, but keeping
+                             -- this as a coercion hole led to #15787
 
 zonk_tycomapper :: TyCoMapper ZonkEnv TcM
 zonk_tycomapper = TyCoMapper
diff --git a/testsuite/tests/polykinds/T15787.hs b/testsuite/tests/polykinds/T15787.hs
new file mode 100644
index 0000000000000000000000000000000000000000..85e737a479eadc48c75d38bd4e7650c2d95bfa92
--- /dev/null
+++ b/testsuite/tests/polykinds/T15787.hs
@@ -0,0 +1,19 @@
+{-# Language RankNTypes #-}
+{-# Language TypeApplications #-}
+{-# Language DataKinds        #-}
+{-# Language PolyKinds        #-}
+{-# Language GADTs            #-}
+{-# Language TypeFamilies     #-}
+
+import Data.Kind
+
+class Ríki (ob :: Type) where
+ type Hom :: ob -> ob -> Type
+
+data
+  Kl_kind :: forall ob . (ob -> ob) -> ob -> Type where
+  Kl      :: k -> Kl_kind (m :: ob -> ob) k
+
+type family
+  UnKl (kl :: Kl_kind m k) = (res :: k) where
+  UnKl (Kl a) = a
diff --git a/testsuite/tests/polykinds/T15787.stderr b/testsuite/tests/polykinds/T15787.stderr
new file mode 100644
index 0000000000000000000000000000000000000000..6d368d5218c05309e8d173325aeae67d7ba2dcce
--- /dev/null
+++ b/testsuite/tests/polykinds/T15787.stderr
@@ -0,0 +1,6 @@
+
+T15787.hs:15:43: error:
+    • Expected kind ‘ob’, but ‘k’ has kind ‘*’
+    • In the second argument of ‘Kl_kind’, namely ‘k’
+      In the type ‘Kl_kind (m :: ob -> ob) k’
+      In the definition of data constructor ‘Kl’
diff --git a/testsuite/tests/polykinds/all.T b/testsuite/tests/polykinds/all.T
index 2d0f993b1760a12d598cadad552de80e27ba7119..53a33e3badd0d6443566260bbb70b4065fce0849 100644
--- a/testsuite/tests/polykinds/all.T
+++ b/testsuite/tests/polykinds/all.T
@@ -193,3 +193,4 @@ test('T15116a', normal, compile_fail, [''])
 test('T15170', normal, compile, [''])
 test('T14939', normal, compile, ['-O'])
 test('T15577', normal, compile_fail, ['-O'])
+test('T15787', normal, compile_fail, [''])