Is there a way to transfer a generic TS argument definition without encountering the "Property doesn't exist on type 'unknown'" error message?

I am puzzled by the fact that doSomething1() and doSomething2() are not being treated equally.

class Example<
    TypeA = void,
    TypeB = void,
    ArgsType = { valueA?:TypeA, valueB?:TypeB }
> {
    valueA?:TypeA;
    valueB?:TypeB;
    
    constructor( valueA:TypeA, valueB:TypeB ) {
        this.valueA = valueA;
        this.valueB = valueB;
    }
    
    doSomething1( args: { valueA?:TypeA, valueB?:TypeB } ) {
        // this works
        const { valueA, valueB } = args;
        
        console.log( valueA );
        console.log( valueB );
    }
    
    doSomething2( args: ArgsType ) {
        // this throws "Property 'valueA' does not exist on type 'unknown'"
        const { valueA, valueB } = args;
        
        console.log( valueA );
        console.log( valueB );
    }
    
}

When I define all parameters manually as in doSomething1(), everything functions as expected. However, when I attempt to consolidate them next to where TypeA and TypeB are defined using a new generic type for arguments, I encounter an error stating

Property 'valueA' does not exist on type 'unknown'
.

This issue seems to be linked to the optional nature of TypeA and TypeB generics, although they remain optional even in manual usage, so what exactly is going on here?

Is there a way to define ArgsType based on optional generics and utilize it in my method declarations?

Answer №1

This particular approach is based on the idea that within ArgsType, you can have {valueA: TypeA, valueB: TypeB}, but alternatively, you could also opt for

{whatever: 999, somethingElse: "Hello"}
.

The validation from the compiler holds true.

To implement it, you would proceed as follows:

interface ArgsType<A, B> {
  valueA: A;
  valueB: B;
}

class Example<TypeA = void, TypeB = void, T extends ArgsType<TypeA, TypeB> = ArgsType<TypeA, TypeB>> {

  valueA: TypeA;
  valueB: TypeB;

  constructor(a: TypeA, b: TypeB) {
    this.valueA = a;
    this.valueB = b;
  }

  doSomething1(args: {valueA?: TypeA, valueB?: TypeB}) {
    const { valueA, valueB } = args;
    
    console.log( valueA );
    console.log( valueB );
  }

  doSomething2(args: T) { // T extends ArgsType<TypeA, TypeB>
    const { valueA, valueB } = args;
    
    console.log( valueA );
    console.log( valueB );
  }
}

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

What are the steps to showcase the content of a Typescript file on an HTML webpage?

We are looking to create a sample gallery with source code examples. Including typescript, html, and HTML files to showcase similar to the Angular.io component samples pages. Is there a way to extract the source code from a typescript file within our pro ...

Delivering static HTML routes in a React App using Typescript

I am working on a React app with functional components, and everything is working perfectly with its own CSS. Now, I have a separate static HTML file (FAQ) with its own CSS and design that I want to incorporate as a new route at /FAQ. I don't want th ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

Encountering a compiler error due to lack of patience for a promise?

In the current TypeScript environment, I am able to write code like this: async function getSomething():Promise<Something> { // ... } And later in my code: const myObject = getSomething(); However, when I attempt to use myObject at a later po ...

Encountering an issue when utilizing inversifyJS inject with the error message "Reading '_userService' cannot be done as it is undefined."

I'm currently working on implementing a DI system, but it seems like I may be missing some key concepts of Inversify. Do I need to create a "get" method for the "user.controller" and then "bind" it to the routes function? Link to complete code reposi ...

Encounter an error message "Expected 0 type arguments, but received 1.ts(2558)" while utilizing useContext within a TypeScript setting

Encountering the error mentioned in the title on useContext<IDBDatabaseContext> due to the code snippet below: interface IDBDatabaseContext { db: IDBDatabase | null } const DBcontext = createContext<IDBDatabaseContext>({db: null}) Despite s ...

Listening for value changes on a reactive form seems to be a challenge for me

While attempting to listen for value changes on a reactive form, I ran into the following error: This expression is not callable. Type 'Observable<string | null>' has no call signatures. searchWord = this.fb.group({ word: ['' ...

How can I prevent buttons from being created using ngFor in Angular?

I need help with creating an HTML table that includes a cell with a button and a dropdown generated using ngFor. How can I disable the buttons (generated via ngFor) if no value is selected from the dropdown? Here's what I have tried so far: In my App ...

Exploring the Contrast in Typescript: Static Members within Classes vs Constants within Namespace

When creating this namespace and class in Typescript, what distinguishes the two? How does memory management vary between them? export namespace TestNamespace { export const Test = 'TEST'; export const TestFunction = (value:string):boolean = ...

Error: Unused variable: '_' has been declared but not utilized

While working on my Next.JS project with TypeScript, I encountered an issue when trying to run the build. The error message stated: Type error: '_' is declared but its value is never read. I attempted to resolve this by setting "noUnusedLocals" ...

AddRange allows the public to add multiple items to the list

Recently, while examining some of my legacy C# code, I came across the following snippet: private List<MyClass> mList = new List<MyClass>(); public List<MyClass> getList() { List<MyClass> list = new List<MyClass>(); li ...

Encountering an issue with Angular 4 polymorphism: Getting an error stating, "Cannot find field 'childs' on the parent type while attempting to interpolate."

I am struggling to implement polymorphism in my Angular 4 project. Unfortunately, I am encountering an error when trying to access a member in a child class. The error message thrown by the compiler 'ng build --prod' is: /$$_gendir/app/app.compon ...

TypeScript error TS6053: Unable to locate file '.ts'

I encountered the following issue: Error TS6053: Could not find file 'xxx.ts'. Oddly enough, the file compiled without any issues yesterday. However, today it seems to be causing trouble. To troubleshoot, I ran a simple test: class HelloWorl ...

Inform the Angular2 Component regarding the creation of DOM elements that are placed outside of the

The Challenge In my Angular2 project, I am using Swiper carousel and building it with Webpack. However, Angular2 adds random attributes like _ngcontent-pmm-6 to all elements in a component. Swiper generates pagination elements dynamically, outside of Ang ...

I'm having trouble importing sqlite3 and knex-js into my Electron React application

Whenever I try to import sqlite3 to test my database connection, I encounter an error. Upon inspecting the development tools, I came across the following error message: Uncaught ReferenceError: require is not defined at Object.path (external "path ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

Encountering an error with type mismatch for style transform properties while using react-native-reanimated

Currently working with the following versions: "react-native": "0.59.10" "react-native-reanimated": "^1.3.0" using TypeScript Encountering a type error related to transform properties. const Example = () => { const { translationX, gestureHandler } = ...

Tips for displaying an array and iterating through its children in Angular 7

I am currently working on extracting the parent and its children to an array in order to display them using ngFor. However, I am encountering an issue where the children are not being displayed during the ngFor. I have a service that retrieves data from a ...

What is the best way to restrict the maximum number of items stored in local storage?

I'm creating a GitHub search app using the GitHub API in Angular. I want to restrict the number of items that can be stored in local storage. If the number of stored elements exceeds 5, the "Add to Favorite" button should either stop working or disapp ...

Determine element height in Angular 5 by clicking on it

Currently, I am experimenting with determining the height of an element that I click on within a sidebar. The purpose is to display submenus accordingly. Below is the code snippet that I am working on: <li (click)="newsExpanded = !newsExpanded; getMarg ...