Creating a distinct Output type in Typescript to avoid any confusion between Output arguments and Input arguments

Inspired by C#, I am looking to define the following:

type FunctionOutput<T> = T; // This is a basic implementation that needs improvement
type Result = {result: number};

function myFun(a: number, b: number, c: FunctionOutput<Result>)
{
   c.result = a + b;
}

c: Result = {};
// What modification should be made in the FunctionOutput type to prompt an error in the following function call:
myFun(1, 2, c) // This should give Error: c is not of type FunctionOutput<Result>

// To ensure correct function call syntax, it would look like this:
myFun(1, 2, c as FunctionOutput<Result>);
console.log(c.result);   // Outputs 3

My goal here is to clearly distinguish the output parameter in the function call and prevent users from mistakenly treating it as an input argument. The main question being:

How do I properly define the FunctionOutput type?

Answer №1

When working with Typescript, it is important to understand its structural types concept. In order for one type to be unassignable to another, they must have differing properties. To ensure that a type like FunctionOutput<T> can only be used with a type assertion c as ..., you can add a property that no real value will ever possess. For instance:

type FunctionOutput<T> = T & { __brand: 'FunctionOutput' }

At runtime, the object c will not actually contain the __brand property. However, since this property will never be accessed, it does not pose any issue.

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

Definition duplication is necessary for TypeScript object properties

I'm currently facing a challenge with TypeScript as I attempt to develop a function that properly assigns default values for an optional object within another object. Even though I am setting up everything in the parameters, I keep encountering an er ...

Utilizing Array in ReactJS with the Power of Hooks

My current situation involves having an array of FooBar objects interface FooBar { foo: string, bar: string, correct: string, other: string[] } const [arrOfObj, setArrOfObj] = useState<FooBar[]>([ { "foo": "fool ...

What is the best way to search for and isolate an array object within an array of objects using Javascript?

I am attempting to narrow down the list based on offerings const questions = [ { "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]}, { "id": 1505, "offerings": [ ...

The process of extracting all arrays from a JSON object

Within my JSON object, there is a list of countries each with multiple regions stored in an array. My goal is to extract and combine all the regions into one single list. However, when I attempt to map the data, it does not consolidate all the regions as e ...

A guide on incorporating typings for d3-tip in TypeScript 2.0

Seeking to implement tooltips in my charts using the d3-tip library. After installing typings for d3-tip in Typescript 2.0: npm install @types/d3-tip --save The typings appear in my package.json: "dependencies": { "@types/d3": "^4.7.0", "@types/d3- ...

Encountering issues with Socket.io: consistently experiencing websocket connection failures along with persistent 404 errors on the

I am facing issues with setting up a websocket using socket.io. The server-side seems to be making a GET call successfully, but on the client-side, I am getting a 404 error: GET http://localhost:6543/socket.io/?uuid=258c4ab9-b263-47ca-ab64-83fe99ea03d4& ...

Tips for automatically adjusting the row height in a table with a static header

On my page, I have a header, footer, and a single table with a fixed header. You can check out the code in the sandbox (make sure to open the results view in a new window). Click here for the code sandbox I am looking to extend the rows section so that i ...

Instance property value driven class property type guard

Is it possible to create a class example that can determine the config type based on the value of animalType instance: enum Animal { BIRD = 'bird', DOG = 'dog', } type Base = { id: number } // Object example type Smth = Base & ...

What is the best way to retrieve information from multiple pages of my REST API?

Recently, I integrated a search engine into my application and now I need to gather all the data available for a particular resource, such as all the posts made by a user. The response I receive from my API looks something like this: { "count": 2, ...

What is the best way to utilize Typescript when making queries to Firebase?

I have successfully integrated push notifications for my app using Firebase Cloud Functions. Now, I am looking to enhance the user experience by updating the app's badge count alongside the push notifications. I understand that this can only be achiev ...

The Typescript Select is displaying an incorrect value

Here's the code snippet I've been working with: <select #C (change)="changeSelect(zone.id, C.value)"> <option *ngFor="let town of townsLocal" [attr.value]="town.data" [attr.selected]="town.data === zone.town && 'selected& ...

Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently, If I try, console.log(keycloak) it will display the entire keycloak object. Even after reloading, it remains in the console. However, when I do, console.log(keycloak.t ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

Turning an array of strings into a multidimensional array

I have a JavaScript string array that I need to convert into a multidimensional array: const names = [ "local://john/doe/blog", "local://jane/smith/portfolio", "as://alexander/wong/resume" ]; The desired output sh ...

What is the best way to programmatically generate a service within Angular?

Is there a way to dynamically create services at runtime using a string name (like reflection)? For example: let myService = new window[myClassName](myParams); Alternatively, you could try: let myService = Object.create(window[myClassName].prototype); m ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

Having trouble getting navigation to work using react-navigation and typescript in a react-native project?

Currently, I am exploring the use of TypeScript in my React Native project for the first time. While I have a basic understanding of TypeScript, I am encountering some issues with third-party libraries like react-navigation. My project consists of parent ( ...

Accessing the value of a FormControl in HTML代码

Modifying the value of a form select element programmatically presents an issue. Even after changing the value in the form, the paragraph element "p" remains hidden. However, if you manually adjust the form's value, the visibility of the "p" element ...

What is the reason behind a tuple union requiring the argument `never` in the `.includes()` method?

type Word = "foo" | "bar" | "baz"; const structure = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFunction = (key: keyof typeof sche ...