diff --git a/gcc/cp/semantics.cc b/gcc/cp/semantics.cc
index 3299e2704465b498001842f0904285be4b756e6f..57840176863bf9161c637ffdfb0a3d4f13ba7900 100644
--- a/gcc/cp/semantics.cc
+++ b/gcc/cp/semantics.cc
@@ -4650,20 +4650,19 @@ finish_type_pack_element (tree idx, tree types, tsubst_flags_t complain)
 	error ("%<__type_pack_element%> index is not an integral constant");
       return error_mark_node;
     }
-  HOST_WIDE_INT val = tree_to_shwi (idx);
-  if (val < 0)
+  if (tree_int_cst_sgn (idx) < 0)
     {
       if (complain & tf_error)
 	error ("%<__type_pack_element%> index is negative");
       return error_mark_node;
     }
-  if (val >= TREE_VEC_LENGTH (types))
+  if (wi::to_widest (idx) >= TREE_VEC_LENGTH (types))
     {
       if (complain & tf_error)
 	error ("%<__type_pack_element%> index is out of range");
       return error_mark_node;
     }
-  return TREE_VEC_ELT (types, val);
+  return TREE_VEC_ELT (types, tree_to_shwi (idx));
 }
 
 /* Implement the __direct_bases keyword: Return the direct base classes
diff --git a/gcc/testsuite/g++.dg/ext/type_pack_element4.C b/gcc/testsuite/g++.dg/ext/type_pack_element4.C
new file mode 100644
index 0000000000000000000000000000000000000000..aa508c79090b9fadf41edf5e58e2588316d9e2f5
--- /dev/null
+++ b/gcc/testsuite/g++.dg/ext/type_pack_element4.C
@@ -0,0 +1,17 @@
+// PR c++/113834
+// { dg-do compile { target c++17 } }
+
+template <typename... _Elements> class tuple{};
+template <unsigned long __i, typename... _Elements>
+__type_pack_element<__i, _Elements...> &get(tuple<_Elements...> &__t) noexcept; // { dg-error "index is out of range" }
+tuple<int,int> data;
+template <unsigned long Level>
+unsigned take_impl(unsigned idx) {
+  if constexpr (Level != -1){
+    return take_impl<Level - 1>(get<Level - 1>(data)); // { dg-error "" }
+  }
+  return 0;
+}
+int main() {
+  take_impl<2>(0);
+}