Employ a type as a function in Typescript programming

Looking for a way to convert an ID into an object using a specific type. The type accepts personId as a string parameter and returns either a Person or undefined.

export type FindPerson = (personId: string) => Person | undefined;

I have multiple person IDs and want to use this type to convert them to Person objects. However, my attempt did not work as expected - it returned a FindPerson object instead of a Person object.

const person = { personId: "1923-01-01a" } as unknown as FindPerson;

Is there a way I can utilize the above type again to successfully obtain a Person object by ID?

Answer №1

When you define a type, it simply describes the type of a function without actually implementing any functionality. Therefore, you cannot use it directly to convert a string to a Person | undefined because it doesn't perform any action; it only indicates what should happen if a function is created. Types do not exist at runtime (except for enums which have some presence). A type itself cannot perform value conversion, although types can convert other types.

To achieve the desired conversion from a string to either a Person or undefined, you will need to create a function that handles this task. Here's an example:

const findPerson: FindPerson = (personId: string) => {
    // ...implementation code...
};

The following snippet provides context with placeholder and stand-in code:

// Placeholder
type Person = {
    id: string;
    name: string;
}

// Your type
/*export*/ type FindPerson = (personId: string) => Person | undefined;

// Stand-in data storage for persons
const personStore: Map<string, Person> = new Map();
function addPerson(id: string, name: string) {
    personStore.set(id, {id, name});
}
addPerson("1923-01-01a", "Joe Bloggs");
addPerson("1924-01-01b", "Mohammed bin Ammar");
addPerson("1925-01-01c", "Constanza Alvares");

// Defining the actual function
const findPerson: FindPerson = (personId: string) => {
    return personStore.get(personId);
};

// Example usage
const person = findPerson("1923-01-01a");
console.log(person);
console.log(findPerson("1924-01-01b"));
console.log(findPerson("no-such-person"));

Playground link

A type like FindPerson proves most useful when:

  1. You want to prevent coding errors during maintenance, such as adding incorrect parameters or altering the function's behavior incorrectly. This is especially helpful when multiple functions share the same interface.

  2. You already have a function, but the parameter names are unclear and could benefit from renaming. For instance, using findPerson like this:

    const findPerson: FindPerson = personStore.get.bind(personStore);
    

    Without the type annotation, the parameter hint would be "key" inherited from the type of Map.prototype.get. With the type annotation, it becomes more specific as "personId."

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

Merging declarations fails to function properly following the release of the npm module

The file core.ts contains the definition of a class called AnyId. In another file named time.ts, more methods are added to the AnyId class. This is achieved by extending the type of AnyId using declaration merging: declare module './core' { in ...

Exploring ways to expand the theme.mixins feature in MUI 5

Currently, I am in the process of updating Material UI from version 4 to 5 and encountering challenges with my existing theming. Since we are using typescript, it is important to include the appropriate types when extending themes. I intend to include th ...

Simple steps for Mocking an API call (Get Todos) using ComponentDidMount in React with Typescript, Jest, and Enzyme

About the application This application serves as a basic To Do List. It retrieves tasks from an API located at https://jsonplaceholder.typicode.com/todos?&_limit=5. Objective of the project The main goal is to test an API call that triggers ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

Getting object arguments from an npm script in a NodeJS and TypeScript environment can be achieved by following these steps

I'm trying to pass an object through an NPM script, like this: "update-user-roles": "ts-node user-roles.ts {PAID_USER: true, VIP: true}" My function is able to pick up the object, but it seems to be adding extra commas which is ...

Add a calendar icon to the DateRangePicker in React Mui

I am trying to set up a DateRangePicker using Material UI with a calendar icon. Here is an example of how I want it to look: https://i.stack.imgur.com/LnYnY.png After following the API documentation and using this code: components={{ OpenPickerIcon: Cal ...

If I include the Next.js Image component within a React hook, it may trigger the error message "Attempting to update state on an unmounted component in React."

My UI layout needs to change when the window width changes. However, when I add an Image (Nextjs component) in my hook, I encounter an error message. I am not sure why adding Image (Nextjs component) is causing this problem. The error message is display ...

Where can I locate the newest Typings definitions?

After switching to Typings for Typescript, I've encountered a frustrating issue where upgrading libraries often leads to deprecated typings. The warning during npm install only mentions that a specific typings item is no longer supported. I have spen ...

Can a custom type guard be created to check if an array is empty?

There are various methods for creating a type guard to ensure that an array is not empty. An example of this can be found here, which works well when using noUncheckedIndexedAccess: type Indices<L extends number, T extends number[] = []> = T["le ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Struggling to refine the result set using jsonpath-plus

Utilizing the jsonpath-plus module (typescript), I am currently working on navigating to a specific object within a json document. The target object is nested several levels deep, requiring passage through 2 levels of arrays. When using the following jsonp ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

Navigating the use of property annotations in Mapped Types with remapped keys

After exploring the concept of Key Remapping in TypeScript, as shown in this guide, I am wondering if there is a way to automatically inherit property annotations from the original Type? type Prefix<Type, str extends string> = { [Property in keyo ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

Using Angular to create a dynamic form with looping inputs that reactively responds to user

I need to implement reactive form validation for a form that has dynamic inputs created through looping data: This is what my form builder setup would be like : constructor(private formBuilder: FormBuilder) { this.userForm = this.formBuilder.group({ ...

Having trouble with the "Vs Code nx console generate" command? It seems that there are no flags available to configure

My issue involves the nx console extension installed in my Visual Studio Code. Every time I attempt to use the generate command for components, services, or libraries, I receive an error message stating "ng generate @schematics/angular:component This com ...

What are the solutions for handling undefined data within the scope of Typescript?

I am encountering an issue with my ngOnInit() method. The method fills a data list at the beginning and contains two different logic branches depending on whether there is a query param present (navigating back to the page) or it's the first opening o ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...

Trouble arises from the object data type not being properly acknowledged in TypeScript

In the code snippet provided, I am facing a challenge where I need to pass data to an if block with two different types. These types are handled separately in the if block. How can I make TypeScript understand that the selected object could be either of ty ...