Is it possible to ensure that function types have "no unexpected properties"?

When specifying the return type of a function, including a property in the returned object that is not part of the return type will result in a type error, indicating that object literals may only specify known properties.

// Type '{ status: string; bar: string; }' is not assignable to type '{ status: string; }'.
// Object literal may only specify known properties, and 'bar' does not exist in type '{ status: string; }'.(2322)
const foo = function(): {status: string} {
    return {
        status: '200 OK',
        bar: 'baz', // Issue
    }
}

When defining a function type, failing to include a defined property within the returned object will trigger a type error, signaling that the specified property is missing:

// Type '() => { baz: string; }' is not assignable to type '() => { status: string; }'.
// Property 'status' is missing in type '{ bar: string; }' but required in type '{ status: string; }'.(2322)
const foo: () => {status: string} = function () {
    return {
        // status: '200 OK'
        bar: 'baz',
    }
}

Interestingly, in this context of setting a function type where missing properties are detected, returning an object with additional properties does not lead to a type error:

const foo: () => {status: string} = function () {
    return {
        status: '200 OK',
        bar: 'baz', // No issue
    }
}

  1. Why doesn't the final example generate a type error?
  2. Is there a way to enforce "no extra properties" on the return object using a function type?

Explore on playground

Answer №1

  1. Why doesn't the last example produce a type error?

The absence of a return type declaration in the function allows TypeScript to infer all relevant type information from the function's definition. As a result, the return type is derived from the object literal ({status: string, bar: string}) and is considered a subclass of the expected return type for the variable assignment, making it valid.

  1. Can a function type be used to enforce "no additional properties" on the returned object?

To achieve this restriction, define the function itself similar to how it was presented in your first code block. By doing so, TypeScript will recognize that the function should not include bar when inferring the variable type.

If you prefer explicitly typing the variable instead of relying on TypeScript's inference capability, you can follow this approach using a playground link for reference:

const foo2: () => {status: string} = function (): ReturnType<typeof foo2> {
    return {
        status: '200 OK',
        bar: 'baz',
    };
};

However, the initial code block remains more straightforward in this scenario.

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

Arrangement of code: Utilizing a Node server and React project with a common set of

Query I am managing: a simple react client, and a node server that functions as both the client pages provider and an API for the client. These projects are tightly integrated, separate TypeScript ventures encompassed by a unified git repository. The se ...

Is there a way to transform an angular 2 app.module into ES6 format?

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; //specific imports remov ...

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

Error message: The TypeScript compiler has detected that a variable of type '[][]' cannot be assigned to a variable of type '[]'

I'm facing a challenge with a component that requires an array parameter to display data, along with another array of objects (different type) that also needs to be passed to the component. The prop type for my component is: type ComponentType = { ...

Creating a generic anonymous class in TypeScript can be achieved by specifying the class body

The title might be a bit misleading, but I'm struggling to articulate my issue. I aim to pass a generic class (or just the class body) as an argument to a function. The provided class should then infer its generics automatically. class Builder<EX ...

The compiler error TS2304 is indicating that it cannot locate the declaration for the term 'OnInit'

I successfully completed the Angular superhero tutorial and everything was functioning properly. However, when I close the CMD window running NPM and then reopen a new CMD window to reissue the NPM START command, I encounter two errors: src/app/DashBoard ...

The value is successfully stored in the component.ts file but is unable to be displayed on the

After successfully retrieving data and logging it in the console of the component.ts file, I encountered an issue where the data is not displaying on the template. My goal is to present the data in a table, but for now, I am attempting to show it within a ...

Mocking Dependencies in TypeScript with Jest

Here is the content of my index.ts file: import {IS3Client, S3Client} from './client/S3Client'; const s3: IS3Client = new S3Client(); export async function someFunc(event: any, context: any, callback: any) { const x: string = await s3.getFil ...

Is it considered valid for `Pair` to be an instance of `MonadRec`?

Phil Freeman's paper titled Stack Safety for Free introduces the MonadRec type class with the following definition. class (Monad m) <= MonadRec m where tailRecM :: forall a b. (a -> m (Either a b)) -> a -> m b Any instance of the MonadR ...

Router-outlet @input decorator experiencing issues with multiple components

Within my router module, I have a route set up for /dashboard. This route includes multiple components: a parent component and several child components. The data I am trying to pass (an array of objects called tablesPanorama) is being sent from the parent ...

An issue has occurred while attempting to differentiate '[object Object]'. Please note that only arrays and iterable objects are permitted

myComponent.component.ts ngOnInit() { this.getData.getAllData().subscribe( response => { console.log(response); this.dataArray = response; }, () => console.log('there was an error') ); } myservi ...

What is the process of retrieving a string in a method within an Ionic TypeScript file and storing it in a variable?

Having trouble returning a string to another method in an Ionic TypeScript file. Our goal is to return JSON.stringify(res) and assign it to the stringset variable. We initially tried testing by simply returning the string "hi", but even that did not work. ...

Error in Typescript: Draggable function is undefined

I'm currently working with typescript alongside vue and jquery ui. Encountering the error "TypeError: item.$element.draggable is not a function". What am I doing wrong in my code? I have already included jquery-ui, as shown in the following files. M ...

What is the best way to extract and connect data from a JSON file to a dropdown menu in Angular 2+?

Here is an example of my JSON data: { "Stations": { "44": { "NAME": "Station 1", "BRANCH_CD": "3", "BRANCH": "Bay Branch" }, "137": { "NAME": "Station 2", ...

There was an error reported by TypeScript stating that Nest.js is not considered a module

During the development of my project using Nest.js, I came across an error that I couldn't find a solution for. The issue arises when I try to export a function from one file and import it into a controller. Even though the function is exported correc ...

What is the best way to change `props.children` into a JSX element?

When using React functional components, we have the ability to render children in the following way: import React from 'react'; const MyComponent = (props: React.PropsWithChildren) => { return props.children; } However, I encountered an ...

Exploring cartography in Typescript

I'm struggling a bit with working on maps in Typescript. My goal is to use a HashMap similar to what's available in Java. For example, here is an example of my Java object: public class Payment { private String id; private DateTime creat ...

Tips for determining the return type when a function yields various promise types

A scenario in which a function returns a Promise with two different potential types based on the parameters passed to it: async function myFunction(buf: boolean): Promise<Buffer | string> { const bytes = "00"; if (buf) { ret ...

What is the best way to retrieve the value of templated objects in TypeScript that refer to another object?

As a novice in typescript, I am seeking guidance on the most efficient method to accomplish this task using typescript: I have a map object that serves as a field mapping tool for combining two objects: source and target. The map object remains unalterab ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...