Can we categorize various types by examining the characteristics of an object?

Is it feasible with TypeScript to deduce the result below from the given data:

const data = {
  field1: {values: ['a', 'b', 'c']},
  field2: {values: ['c', 'd', 'e'], multiple: true}
}

const fields = someFunction(data)

By analyzing if multiple exists and its boolean value, can we derive the return value of someFunction (and subsequently the type of fields) as shown here?

type FieldsType = {
  field1: 'a' | 'b' | 'c',
  field2: ('c' | 'd' | 'e')[]
}

If necessary, data can be defined as as const.

Answer №1

To start, define a type for your source data:

type Data = Record<string, {
  values: readonly string[],
  multiple?: boolean
}>

Next, create a conditional type that is mapped to accept the defined type:

type Fields<T extends Data> = {
  [K in keyof T]:
    T[K]['multiple'] extends true
      ? T[K]['values'][number][]
      : T[K]['values'][number]
}

This conditional type iterates over all keys in T (such as field1 and field2) and determines the value type of each property based on a condition.

The condition states that if T[K]['multiple'] extends true, then return an array containing the specified member types from the values property, otherwise return a non-array of that type.

You can now utilize this type as follows:

function someFunction<T extends Data>(data: T): Fields<T> {
  // TODO: implement this
}

This function works as expected:

const fields = someFunction({
  field1: { values: ['a', 'b', 'c'] },
  field2: { values: ['c', 'd', 'e'], multiple: true }
} as const)

fields.field1 // ('a' | 'b' | 'c')[]
fields.field2 // 'a' | 'b' | 'c'

Explore Playground Here

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

Troubleshooting Python Error: Converting Dataframe Columns with astype Function

Struggling to convert a column format using astype to int64, but encountering the following error: "ValueError: invalid literal for int() with base 10: '75.01'" Here's the code snippet: import pandas as pd import http.client impo ...

The best location for storing Typescript files within an ASP.NET Core project

My Typescript app is built on AngularJS 2 with ASP.NET Core, and currently I store my TS files in the wwwroot directory. While this setup works well during development, I am concerned about how it will function in production. I aim to deploy only minified ...

After compilation, any variables declared within a module remain undefined

I have declared the following files app.types.ts /// <reference path="../../typings/tsd.d.ts"/> module App{ export var Module = "website"; //---------------Controller Base Types--------------- export interface IScope extends ng.ISco ...

Angular's Spanning Powers

How can I make a button call different methods when "Select" or "Change" is clicked? <button type="button" class="btn btn-default" *ngIf="!edit" class="btn btn-default"> <span *ngIf="isNullOrUndefined(class?.classForeignId)">Select</spa ...

What could be the reason why the getParentWhileKind method in ts-morph is not returning the anticipated parent of the

Utilizing ts-morph for code analysis, I am attempting to retrieve the parent CallExpression from a specific Identifier location. Despite using .getParentWhileKind(SyntaxKind.CallExpression), the function is returning a null value. Why is this happening? I ...

Tips for sending a value to a container component

Within my task management application, I have implemented two selectors: export const selectFilter = (state: RootState) => state.visibilityFilter export const selectVisibleTodos = createSelector( [selectTodos, selectFilter], (todos: Todo[], filter : ...

Is there a way to utilize ng-if within a button to reveal the remaining portion of a form using TypeScript?

Can anyone help me figure out how to make the rest of my form appear when I click on a button? I think I need to use Ng-if or something similar. Here is the code for the button: <button type = "button" class="btn btn-outline-primary" > Données du ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Setting a default value for a complex prop in Vue through Type-based props declarations

I'm struggling with this issue: Argument of type 'HelloWorldProps' is not assignable to parameter of type 'InferDefaults<LooseRequired<HelloWorldProps>>'. Types of property 'complexProp' are incompatible.ts( ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

How is it possible to leverage the CDN URL mechanism for package management when working with Typescript?

Is it possible to use a CDN URL pointing mechanism to resolve packages in Typescript? One example is the Material Icon package installation, which can be included using the following code: <link rel="stylesheet" href="https://fonts.googleapis.com/icon? ...

I find that the value is consistently undefined whenever I attempt to set it within a promise in Angular

Hi there, I've encountered an issue with my getData() function in accountService.ts. I'm attempting to fetch user data and user account data simultaneously using a zip promise. Although the resolve works correctly and I receive the accurate data, ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

The functionality to close the Angular Material Dialog is not functioning as expected

For some reason, I am facing an issue with closing a dialog window in Angular Material using mat-dialog-close. I have ensured that my NgModule has BrowserAnimationModule and MatDialogModule included after checking online resources. Your assistance with t ...

Angular: ngx-responsive has a tendency to hide elements even if they meet the specified conditions

Recently, I started using a library called this to implement various designs for desktop and mobile versions of an Angular app (v4.2.4). Although the documentation recommends ngx-responsive, I opted for ng2-responsive but encountered issues. Even after set ...

Develop a query builder in TypeORM where the source table (FROM) is a join table

I am currently working on translating this SQL query into TypeORM using the QueryBuilder: SELECT user_places.user_id, place.mpath FROM public.user_root_places_place user_places INNER JOIN public.place place ON place.id = user_places.place_id The ...

What is the purpose of specifying the props type when providing a generic type to a React functional component?

When utilizing the @typescript-eslint/typedef rule to enforce type definitions on parameters, I encountered an issue with generically typing a React.FC: export const Address: React.FunctionComponent<Props> = (props) => ( An error was thrown st ...

Is there a way to customize the language used for the months and days on the DatePicker

Is there a way to change the language of the DatePicker (months and days) in Material UI? I have attempted to implement localization through both the theme and LocalizationProvider, but neither method seems to work. Here are some resources I have looked a ...