Most, if not all statically typed languages allow you to specify a single type for a function or constructor parameter; for example
function foo(x: string) { ... }
foo("hello") // works
foo(123) // error
TypeScript is a statically typed super-set of JavaScript, but since JavaScript is a dynamically typed language, TypeScript allows you to be a little more flexible; for example, you can specify more than one allowable type.
function foo(x: string | number) { ... }
foo("hello") // works
foo(123) // works
foo(true) // error
Additionally, in TypeScript this allows you to constrain generic type parameters to specific types only; for example:
class Foo<T extends number | string> {
constructor(x: T) { ... }
}
new Foo("hello") // works
new Foo(123) // works
new Foo(true) // fails
Problem
I like TypeScript's ability to constrain generic type parameters to specific types only, but I would also like to be able to do this in other languages, namely C# and Kotlin, but as far as I am aware, there is no equivalent construct in these languages to support such a constraint. How would one achieve this in other languages?
Note: I'm happy to accept answers in any language, not just the ones listed. This is more about higher level thinking and exploring other avenues which could apply across languages.