Is it possible to declare the type of an object within a function call?

When working with TypeScript, it is possible to define a function and an interface like this:

function someFunction(options: any) {
    // Do something
}

interface MyOptions {
    userId: number;
    verbose: boolean;
}

const options: MyOptions = {
    userId: 12345,
    doesntExist: false, // Error
}

someFunction(options);

If we try to assign a property that doesn't exist in the defined interface, it will result in a compilation error.

However, if we skip creating the intermediate variable and directly pass the object to the function like this:

someFunction({
    userId: 12345,
    doesntExist: false, // no error
});

In this scenario, because the someFunction accepts any as a parameter, type checking is not enforced. Even using as MyOptions won't trigger the compiler to complain.

Therefore, the question arises - is there a way to enforce type checking without the need for creating an intermediate variable?

Answer №1

I was curious if there exists a syntax that allows me to specify "while the function accepts 'any' as input, I assert that the object I'm passing is of type T"

What you are referring to is known as generics.

function someFunction<T>(options: T) {
  // Do something
}

If you call the function without explicitly defining the generic T, TypeScript will infer that T represents the type of the argument provided.

However, by manually specifying the generic as MyOptions, you will receive an error if the argument does not match the expected type.

someFunction<MyOptions>({
  userId: 12345,
  doesntExist: false // error
})

In this case, the error reads Argument of type '{ userId: number; doesntExist: boolean; }' is not assignable to parameter of type 'MyOptions'. Object literal may only specify known properties, and 'doesntExist' does not exist in type 'MyOptions'.

Typescript Playground Link

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

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...

What is the proper way to send a list as a parameter in a restangular post request

Check out this code snippet I found: assignUserToProject(pid: number, selectedUsers: any, uid: number) { let instance = this; return instance.Restangular.all("configure/assign").one(pid.toString()).one(uid.toString()).post(selectedUsers); } ...

Utilize the type correctly within a React Higher Order Component

Having some trouble with types while using an HOC. The following is the code snippet for the HOC: export interface IWithLangProps { lang: ILang; } const withLang = <T extends object>(Comp: React.ComponentType<T>): React.ComponentClass ...

Steps for running a TypeScript project as a child process within a JavaScript project

I am facing an issue with integrating my Electron app, written mainly in JavaScript, with an Express server project built in TypeScript. When I attempt to create a child process of the TypeScript project within my electron.js file, I encounter TypeScript e ...

Navigating global variables and functions in Vue3 with TypeScript

Feeling lost in the world of Vue.js, seeking guidance here. Attempting to handle global data and its corresponding functions has led me on a journey. Initially, I experimented with declaring a global variable. But as more functions came into play, I trans ...

React Typescript Context state isn't refreshing properly

Struggling to modify my context state, I feel like I'm overlooking something as I've worked with context in the past. The challenge lies in changing the 'isOpen' property within the context. You can view my code here: CodeSand **app.ts ...

Tips for sending asynchronous data to Google-Charts-Angular

I am currently working on generating a chart using data obtained from an API call. To achieve this, I am utilizing the google-charts-angular package within my HTML: <google-chart [title]="title" [type]="type" [data]="data" ...

Having trouble retrieving values from Promise.allSettled on Node.js 12 using TypeScript version 3.8.3

Currently, I am delving into NodeJs 12 and exploring the Promise.allSettled() function along with its application. The code snippet that I have crafted allows me to display the status in the console, but there seems to be a hitch when attempting to print t ...

Unable to locate the TypeScript library module within the specified directory

I have been developing a TypeScript NPM package by following instructions from this tutorial You can check out the code here After publishing the NPM package, it is available here Installation of the package is simple using npm install loglevel-file-lo ...

What is the process for importing a map from an external JSON file?

I have a JSON file with the following configuration data: { "config1": { //this is like a map "a": [ "string1", "string2"], "b": [ "string1", "string2"] } } Previously, before transitioning to TypeScript, the code below worked: import ...

What is the correct way to apply type in the .call() method?

I need help finding a solution for the following issue interface IName { name:string; } let obj1:IName = { name: "LINUS" } function profileInfo (age:number,location:string):string{ return `${this.name} is ${age} years old and is from ${location ...

When setting a value that has been explicitly casted, the original literal type remains intact for the new property or variable

After defining the constant MODE with specific values, I noticed something interesting: const MODE = { NONE: 0 as 0, COMPLETED: 1 as 1, DELETED: 2 as 2 } as const // In a CreateReactApp project, enums aren't available It became appar ...

How can arguments be passed via the CLI when constructing an Angular application?

In my current Angular 16 project, I am facing a unique scenario where each machine running the application locally has a different IP address. This means that the server URL will vary for each instance. Currently, I am retrieving this URL from the environm ...

Error in pagination when using MAX() function in PostgreSQL query

Here is the query I am using to retrieve the latest message from each room: SELECT MAX ( "Messages"."id" ) AS messageId, "Rooms"."id" FROM "RoomUsers" INNER JOIN "Rooms" ON " ...

The TypeError: Property 'subscribe' is not readable because it is undefined

Currently, I am developing an Ionic application and encountered the following method that invokes an observable: fetchCountryById(id: number): Promise<Country> { return new Promise((resolve, reject) => { this.obtainCountries().subscri ...

The value of additionalUserInfo.isNewUser in Firebase is consistently false

In my application using Ionic 4 with Firebase/AngularFire2, I authenticate users with the signinwithemeailandpassword() method. I need to verify if it's the first time a user is logging in after registering. Firebase provides the option to check this ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Angular button press

Recently, I started learning Angular and came across a challenge that I need help with. Here is the scenario: <button *ngIf="entryControlEnabled && !gateOpen" class="bottomButton red" (click)="openGate()">Open</button> <button *ngIf ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...