Acquire data on the type from the returned outcome of a function

Below is a function that I am working with in the TypeScript playground:

function myf(): Record<string, string> {
    return {
      prop1: "a",
      prop2: "b"
    }
}

This function is pure and simply returns a dictionary value. My goal is to extract a type definition from the return type of this function, specifically {prop1: string, prop2: string}. I attempted to do so using:

type MyType = ReturnType<typeof myf>;

however, this results in a generic type {[key: string]: string}, which although correct, does not meet my goals:

https://i.sstatic.net/lzZ36.png

If I use my function without specifying a return type as shown below (playground):

function myf() {
    return {
       prop1: "a",
       prop2: "b"
    }
}

I get a valid result:

https://i.sstatic.net/9UEzR.png

However, in this case, I lose type checking on my return value.

My question is, is it possible to have both type checking on the return value and somehow infer the return type outside of the function? Ideally, I would like something similar to the example below (with intellisense for myvar):

https://i.sstatic.net/SakI0.png

Answer №1

By including a return annotation such as : Record<string, string> in the function declaration

function myf(): Record<string, string> {
, TypeScript will always infer the type as Record<string, string>.

Suggestion

Instead of specifying the return type explicitly, you can allow TypeScript to automatically infer it by simply returning an object:

function myf() {
    return {
        prop1: "a",
        prop2: "b"
    }
}

// The inferred type now becomes {prop1: string, prop2: string}
type MyType = ReturnType<typeof myf>;

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

Converting Promises to Observables

Struggling with the syntax as I delve into learning Angular, I need to transform a promise into an Observable. Let me share what I've encountered: In the function getCountries (subscribed by another utility), there is a call required to fetch a list ...

Mastering GraphQL querying in React using TypeScript

After successfully setting up a graphql and being able to use it in Postmen, here is how it looks: query listByName($name: String!) { listByName(name: $name) { id name sortOrder } } My variable is defined as {"name&quo ...

The shop named 'someStore' is currently unavailable! Please ensure that it is being offered by a valid Provider

I'm having trouble setting up a new project using React, Typescript, and MobX. Despite having a relatively simple piece of code, I can't seem to get MobX to work properly. It keeps showing me this error message: Uncaught Error: MobX injector: S ...

I am unable to nest children within the <Provider> tag when using Typescript Redux

https://i.sstatic.net/hFx3h.png I am encountering this error and I am unsure about the root cause. Any help would be greatly appreciated. Below, I have included a snippet of the code along with the package.json: import React from "react"; ...

Can you explain what comes after the equal sign in a TypeScript object?

While browsing through this response on stackoverflow The author answered: // How I usually initialize var foo:IFoo = <any>{}; I attempted to research it online, but unfortunately, I couldn't find any information about it. Could someone expl ...

What is the best approach for submitting a form with data through a POST request in an Ionic application?

I am facing an issue while trying to make a POST request in Ionic for submitting a form with an array of data. Surprisingly, it works perfectly fine when I test it on POSTMAN. https://i.sstatic.net/t8sEG.jpg Although I attempted to use this form, it did ...

Disregard the JSON formatting and extract solely the values

After extracting data from an API, the format of the returned information looks like this: [{"id":21},{"id":22},{"id":24}] Next, I need to send this data to a database using a different API. However, the format for sending should be like this: [21,22,24] ...

What is the reason behind the failure of a react factory method compilation when extending a typescript class, despite it working perfectly fine on the base class?

As I delve into my lengthy codebase consisting of hundreds of lines, I have managed to narrow down my issue to a concise example. My query pertains to the peculiar behavior exhibited by the Typescript compiler in a specific scenario. The snippet below com ...

What is the process for restoring or installing chai typings that have been specified as devDependencies?

After installing chai typings using the typings tool with the command provided, I am encountering an issue where chai is not being installed on the build server. typings install chai --save-dev The devDependencies section in my typings.json file is as fo ...

Unexpected error arises in Typescript despite code functioning properly

As part of a practice project where I'm focusing on using webpack, ES6, npm and Typescript implementation, I have successfully set up loaders for 'awesome-typescript-loader' and 'babel-loader', which are bundling the code properly. ...

When using the Composition API in Vue 3, the "Exclude" TypeScript utility type may result in a prop validation error

Currently, I am utilizing Vue 3 alongside the Composition API and TypeScript, all updated to their latest stable versions. If we take a look at the types below: export interface Person { name: string; } export type Status = Person | 'UNLOADED&ap ...

Error: The function visitor.visitUnaryOperatorExpr is not defined as a function

I recently started developing an Angular app with a purchased template and collaborating with another developer. Initially, I was able to successfully build the project for production using ng build --prod. However, when trying to build it again yesterday, ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

What is the best approach for resolving this asynchronous task sequencing issue in JavaScript?

Below is a code snippet where tasks are defined as an object and the function definition should ensure the expected output is met. Let tasks = { ‘a’: { job: function(finish){ setTimeout(() => { ...

The limit of update depth when using useState with an array generated from a map operation

I'm working on a component where I'm creating a list from an array using map. Each li element in the list has a ref attached to it to capture the getBoundingClientRect().x and getBoundingClientRect().y coordinates, which are then stored in a refs ...

Stop certain sections of Typescript code from being compiled

In my scenario, I have two classes: class A and class B. Class B extends class A. The issue arises when we consider a method in both classes. Class A has a method that accepts AProperties enum as its first argument. However, class B has a similar method th ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

What causes images to unexpectedly expand to fill the entire screen upon switching routes in Next.js?

I'm in the process of creating a website using Next and Typescript, with some interesting packages incorporated: Framer-motion for smooth page transitions Gsap for easy animations One issue I encountered was when setting images like this: <Link&g ...

The ReferenceError occurs exclusively during the execution of tests

I keep encountering a dull stacktrace after executing my test. I've experimented with solutions like using fakeTimers, require('iconv-lite')..., etc, based on these queries: Encoding not recognized in jest.js ReferenceError: You are trying ...

Tips for having tsc Resolve Absolute Paths in Module Imports with baseUrl Setting

In a typescript project, imagine the following organizational structure: | package.json | tsconfig.json | \---src | app.ts | \---foobar Foo.ts Bar.ts The tsconfig.json file is set up t ...