Universal - Permissible data types for function and constructor arguments

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.

Answer №1

The concept feature in C++20 allows for the constraint of template parameters in a precise manner, going beyond what was previously possible with various techniques. Exploring these techniques is beyond the scope of this discussion.

Answer №2

When using TypeScript, there is a level of flexibility that allows you to specify multiple allowable types.

It's important to note that "number | string" in TypeScript is considered a union type, meaning it encompasses both "number" and "string" as subtypes. This means you can pass either a number or a string, as they fall under the umbrella of "number | string." Additionally, any subtype of "number | string" could also be passed.

In another example, the variable "T" is not limited to only being a "number" or "string"; it can also be "number | string" or any subtype of "number" or "string."

var x = new Foo<123 | "">(123)

In this snippet, "123 | """ represents a standard TypeScript type declaration.

Although Scala 3 will introduce union types, other languages like Kotlin and C# have discussed but shown little interest in incorporating similar features.

Answer №3

F# introduces the concept of Sum / Union types, which bears resemblance to what is found in TypeScript. However, in F#, these types are defined with labels that are used for matching purposes.
This feature allows you to create sum types with multiple cases of the same type. Here's an example:

type ShoeSize = 
    | EU of double
    | UK of double
    | US of double

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...

While the data from Angular $resource can be viewed, it is not accessible in the code

As a newcomer to Angular, I'm facing a frustrating issue that I need help with. My $resource is fetching data from the server in key/value pairs like detail.name and detail.email. While I can access this data using {{detail.name}} in the view, I&apo ...

Tips for using the .innerHTML method to reference multiple indexes

How can I set the .innerHTML for multiple indexes of an array? I currently have an array let poles = Array.prototype.slice.call(document.querySelectorAll(".pole")); This array contains 9 empty divs, such as : <div class="pole" id="1"></div> ...

What is the best way to adjust the size of my Leaflet map within a Bootstrap collapse module in my Dash application?

I am currently working on integrating a bootstrap collapse element that contains a leaflet map. My goal is to toggle the map view open and closed, but I have encountered an issue where the map does not resize properly when the collapse item is opened. As a ...

Switching from Dom to Jquery

Seeking assistance to convert DOM values into Jquery equivalent. For instance, how can I translate the DOM code: var x = document.querySelector('#x'); into Jquery format? Any suggestions? Additionally, looking for guidance on transforming even ...

JavaScript code to retrieve an image from an <img> tag's source URL that only allows a single request and is tainted due to cross-origin restrictions

I have an image displayed in the HTML DOM. https://i.stack.imgur.com/oRgvF.png This particular image (the one with a green border) is contained within an img tag and has a URL as its source. I attempted to fetch this image using the fetch method, but enc ...

Express API encounters an issue with multer and body-parser as req.file is undefined

I am in the process of developing an API that will need to handle file uploads along with other GET and POST requests. To manage file uploads, I am using 'multer' while utilizing 'body-parser' for all other HTTP requests. My goal is to ...

Prepare yourself for the possibility of receiving a caution while within a try-catch block

After implementing the MongoClient.connect method and encountering the warning 'await' has no effect on the type of this expression, it became clear that including the .catch line immediately following (which is currently commented out) mitigated ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

Ways to take an item out of your shopping cart

Do you have any ideas on how to handle cart redirection in JavaScript? My specific request involves a cart with a function that removes products. What approach should I take to redirect to the main page if the cart becomes empty? Here is the delete produc ...

Concealing Query Parameters in MVC Controller Action

Looking for a way to conceal the Querystring within my controller's action. Here is how my application scenario plays out: 1) I have initiated a new action in a new Window using the following code: var check = "Particular String" var url = rootUr ...

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...

Dealing with asynchronous operations in a pipeline with fp-ts

I'm currently exploring fp-ts and have been contemplating how to restructure my functions in order to steer clear of nested folds. While many online examples showcase a clean invocation of the pipe function, I am struggling to eliminate the nested fol ...

Assign the ngClick event handler to the capturing phase

Can the ngClick event handler be configured to work in the capturing phase, as discussed in this informative article? I am interested in stopping events from propagating down to child elements and then back up again when a specific condition is met for t ...

Updating the defaultLabel dynamically in primeNg multiselect: A step-by-step guide

In the PrimeNG multiselect component, I'm facing an issue where I can unselect items from the TypeScript file, but this change is not reflected in the input field. someComponent.html <p-multiSelect [options]="cities1" maxSelectedLabels=0 selected ...

javascript - determine whether a hyperlink has been accessed

Is there a method to determine if a link has been visited? In Firefox, the color of a link changes after clicking on it, which leads me to believe it is possible. Edit: This question pertains to a Firefox extension, so I am unable to modify the HTML or CS ...

Issue encountered during the creation of a Nuxt3 project. The download of the template from the registry was

Trying to create a new Nuxt 3 project using the command below: npx nuxi init nuxt-app The following error message is displayed: ERROR (node:1752) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time ...

Shifting HTML table in Javascript by toggling checkboxes

When I click the checkbox, the table elements are not displaying inline. I am simply hiding the class "box". Do I need to write a special format? By default, the elements are displayed inline but when I check the checkbox, they shift. The column 'Stat ...

Mongoose does not compare BCRYPT passwords that are empty

I'm currently working on incorporating bcrypt into my mongoose model using typescript. Referencing this link as a guide. However, since my project is in typescript, I'm unable to directly use the provided code. I'm confused about how they&a ...