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

I seem to be invisible to the toggle switch

I currently have a toggle button that controls the activation or deactivation of a tooltip within a table. Right now, the tooltip is activated by default when the application starts, but I want to change this so that it is deactivated upon startup and on ...

What sets React.FC<T> apart from Function() in TypeScript?

Do arrow functions and function notations differ from each other? It seems like these two methods function in the same way. One is written as React.FC<T> while the other as Function(). Is this simply a matter of notation, or are there deeper reaso ...

Retrieving PHP information in an ionic 3 user interface

We are experiencing a problem with displaying data in Ionic 3, as the data is being sourced from PHP REST. Here is my Angular code for retrieving the data: this.auth.displayinformation(this.customer_info.cid).subscribe(takecusinfo => { if(takecusi ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

Upgrading from Angular 5 to 6: Embracing the RxJS Changes without the crutch of rxjs

Currently, I am facing the challenging task of migrating a project from Angular 5.2.11 to version 6.0.0. The main issue I'm encountering is with RxJS 6 (which is essential for Angular versions above 6). Here's an example of one of the errors that ...

MUI DataGrid Identifying Duplicate Rows

I'm encountering an issue with my Data Grid component from MUI when fetching data using axios. The console shows the correct data, but on the page, it only displays one result or duplicates. I suspect there might be a frontend problem, but I'm s ...

What could be causing variations in the performance of my Speech Recognition code each time I run it?

Check out my code snippet: export class voiceRecognition { constructor() { } public startVoiceRecognition() { const recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimresults = false; recogn ...

Leverage environment variables within your index.html file

Currently, I am using Angular and I am encountering an issue while attempting to utilize an environment variable in my index.html for Google Analytics. I have attempted the following approach: <script> import {environment} from "./environments/e ...

Can metadata be attached to data models in Angular for annotation purposes?

Looking to add some metadata annotations to a simple data model export class Certification { title: string; certificationType?: CertificationType; validTo?: number; description?: string; externalIdentifier: Guid; constructor() { ...

Is TypeScript to blame for the unexpected token error in Nock?

My code snippet in the ts file looks like this: nock('https://example.test').post('/submit').reply(200,{ "status": "Invalid", "message": "Invalid Request", }); However, when I try to ...

Discover the solution to the issue of bookmarking a card on a page using react, typescript, and mui!

Whenever I try to favorite a card by clicking on its icon, all cards of the same type get bookmarked instead of just the one I clicked on. This is causing an issue where multiple cards are being favorited per page when I only want to bookmark individual on ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...

Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference: export interface SearchTexts { SearchText: SearchText[]; } export interface SearchText { Value: st ...

The term 'string' is typically employed as a data type, yet in this instance it is being utilized as an actual value

Just started working with TypeScript and encountered an issue while trying to set the state. Encountered this error message: 'string' is a type and cannot be used as a value here. const state = reactive({ user: { uid: "", ...

How to build a login page with a static header and footer using Angular2

For my latest project, I am currently in the process of developing an application using Angular2 and eclipse Neon. Utilizing angular-cli for this app, I am now focused on creating the login page. Within the app.component.html file, you will find the follow ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

Does Typescript extend Node.js capabilities?

I am currently developing an application using Typescript and came across some sample Node.js code online. Can I directly use the Node.js code in my Typescript application? Essentially, I am wondering if Typescript is encompassed within Node.js. A simila ...

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

One approach to enhance a function in Typescript involves encapsulating it within another function, while preserving

What I Desire? I aim to create a function called wrap() that will have the following functionality: const func = (x: string) => 'some string'; interface CustomObject { id: number; title: string; } const wrapped = wrap<CustomObject> ...