In many statically typed languages, it is common to specify a single type for a function or constructor parameter. For example:
function greet(name: string) { ... }
greet("Alice") // works
greet(42) // error
TypeScript is an extension of JavaScript with static typing features. Unlike JavaScript, TypeScript allows for more flexibility by letting you specify multiple allowable types for a parameter. Here's an example:
function greet(name: string | number) { ... }
greet("Bob") // works
greet(25) // works
greet(true) // error
Furthermore, in TypeScript, this flexibility extends to constraining generic type parameters to specific types only, as shown here:
class Person<T extends number | string> {
constructor(name: T) { ... }
}
new Person("Charlie") // works
new Person(30) // works
new Person(true) // fails
An Issue
I appreciate TypeScript's feature of constraining generic type parameters to specific types, but I would like to achieve similar behavior in other programming languages such as C# and Kotlin. To my knowledge, there isn't a direct equivalent mechanism in those languages that supports this constraint. How can one replicate this functionality in other languages?
Note: Answers in any programming language are welcome, not limited to the ones mentioned. This question aims to explore diverse approaches that could be applied universally across different languages.