Transform the property of type any/unknown into a specific generic type T within the map

Suppose I start with...

type TypeNonGeneric = { prop1: any, prop2: string };

How do I transform it into...

type TypeGeneric<T> = { prop1: T, prop2: string };

I have reviewed the documentation and it appears that I need to create a new generic type that accepts TypeNonGeneric as an input, iterates through its properties, and replaces any instance of any with "T", while keeping all other types unchanged.

Answer №1

To tackle this problem, I recommend using the IfAny utility type which can be found in this helpful response. By utilizing this utility type, we are able to iterate through the given type and verify if there are occurrences of the any data type for each property.

type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;

type TypeGeneric<O, T> = {
  [K in keyof O]: IfAny<O[K], T, O[K]>
}

Let's illustrate with an example:

type TypeNonGeneric = { prop1: any, prop2: string };

type Result = TypeGeneric<TypeNonGeneric, number>
// type Result = {
//    prop1: number;
//    prop2: string;
// }

Alternatively, if you wish to replace instances of any with T:

type Result2<T> = TypeGeneric<TypeNonGeneric, T>
// type Result = {
//    prop1: T;
//    prop2: string;
// }

Check out the Playground for further experimentation!

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

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Ways to ensure that your Angular component.ts file is executed only after the body has completely loaded without relying on any external

I am attempting to add an event listener to an element created with a unique identifier using uuid, but I keep getting an error that states "Cannot read properties of null (reading 'addEventListener')" export class CommentItemComponent implements ...

The issue arises when TypeScript declarations contain conflicting variables across multiple dependencies

My current project uses .NET Core and ReactJS. Recently, I updated some packages to incorporate a new component in a .tsx file. Specifically, the version of @material-ui/core was updated from "@material-ui/core": "^3.0.3" to "@material-ui/core": "^4.1.3" i ...

What is the best way to merge imported types from a relative path?

In my TypeScript project, I am utilizing custom typings by importing them into my .ts modules with the following import statement: import { MyCoolInterface } from './types' However, when I compile my project using tsc, I encounter an issue wher ...

Error encountered when extending Typography variant in TypeScript with Material UI v5: "No overload matches this call"

Currently, I am in the process of setting up a base for an application using Material UI v5 and TypeScript. My goal is to enhance the Material UI theme by adding some custom properties alongside the default ones already available. The configuration in my ...

Having trouble typing computed values in Vue Composition API with TypeScript?

I'm attempting to obtain a computed value using the composition API in vue, and here is the code I am working with: setup() { const store = useStore(); const spaUrls = inject<SpaUrls>('spaUrls'); const azureAd = inject<AzureAd ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...

Exploring the implementation of method decorators that instantiate objects within Typescript

Currently, I have been working on a lambda project and utilizing the lambda-api package for development. As part of this process, I have implemented decorators named Get and Post to facilitate mapping routes within the lambda api object. These decorators e ...

Typescript: Removing signatures with a filter

I am encountering a TypeScript error stating that .filter has no signatures. I'm unsure of how to resolve this issue. interface IDevice { deviceId: string; deviceName?: string; } const joinRoom = ({ userId, deviceId, deviceName }: IRoomParams ...

Utilize the up and down arrow keys to scroll through a description list in React

If you want to navigate through the list of Description Details using the tab and shift tab keys, it can be done easily. The default behavior allows for smooth navigation. <dl> <dt style={{ textAlign: "center" }}>Beast of Bodmin< ...

Encountering a problem with the 'string' parameter when using TypeScript

I keep encountering the following error message: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ barkingRoadProject: string[]; }'. No index signature with a paramet ...

What would cause the nsfw property to be absent from a TextChannel in client.on("messageCreate") event?

Currently working with Typescript in combination with Discord.js v14, I'm encountering the following error: Property 'nsfw' does not exist on type 'DMChannel | PartialDMChannel | ... Below is the snippet of problematic code: client.on( ...

Dynamic table row that expands to show additional rows sourced from various data sets

Is there a way to expand the table row in an angular-material table when it is clicked, showing multiple sets of rows in the same column as the table? The new rows should share the same column header but not necessarily come from the same data source. Whe ...

Obtain the last used row in column A of an Excel sheet using Javascript Excel API by mimicking the VBA function `Range("A104857

Currently in the process of converting a few VBA macros to Office Script and stumbled upon an interesting trick: lastRow_in_t = Worksheets("in_t").Range("A1048576").End(xlUp).Row How would one begin translating this line of code into Typescript/Office Scr ...

Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions? In the TS 2.8 release notes, we see examples like: type ReturnType<T> = T exten ...

typegrapql encounters an issue with experimentalDecorators

I'm currently delving into TypeGraphQL and working on building a basic resolver. My code snippet is as follows: @Resolver() class HelloReslover { @Query(() => String) async hello(){ return "hello wtold" } } However, ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Encountering NoResourceAdapterError when using @admin-bro/nestjs alongside @admin-bro/sequelize and MySQL?

Encountering a similar issue with '@admin-bro/sequelize' NoResourceAdapterError: No compatible adapters found for the provided resource import { Database, Resource } from '@admin-bro/sequelize'; import { AdminModule } from '@admin- ...