Skip to content
This repository has been archived by the owner on Apr 25, 2023. It is now read-only.

Properly type ngOnSetup method return #2

Open
crutchcorn opened this issue Jan 8, 2021 · 0 comments
Open

Properly type ngOnSetup method return #2

crutchcorn opened this issue Jan 8, 2021 · 0 comments
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@crutchcorn
Copy link
Member

I would love for the ngOnSetup function to enforce the return type of the setup function.

While I would love for the typings to be as simple as:

  ngOnSetup(props: this): Partial<Record<keyof this, any>>

I seem to get errors while doing so:

TS2322: Type '{ test: Ref ; addToPlus: () => void; }' is not assignable to type 'Partial  >'.

What's interesting about this error in particular is that Partial is not a primitive type, but rather a utility type. This makes me think there is a bug in TypeScript


Playing around with the typings, I managed to get this working on the consuming side of things:

  ngOnSetup(props: this): Partial<Record<keyof InstanceType<typeof AppComponent>, any>> {
    const test = ref(12);

    const addToPlus = (): void => {
      test.value += 1;
    };

    return {
      test,
      addToPlus
    };
  }

However, while trying to extract this logic out to a sensible version in the library itself, I saw errors. The following is the closest approximation to the types that I wanted to see:

// lib/Setup.ts
export type SetupReturn<T extends new (...args: any) => any> = Partial<Record<keyof T, any>>;

export declare interface OnSetup {
  ngOnSetup<T>(props: this): SetupReturn<T extends new (...args: any) => any>;
}
// app/app.component.ts

ngOnSetup(props: this): SetupReturn<InstanceType<typeof AppComponent>> {
  const test = ref(12);

  const addToPlus = (): void => {
    test.value += 1;
  };

  return {
    test,
    addToPlus
  };
}

However, this code doesn't work either. I get the following error:

TS2416: Property 'ngOnSetup' in type 'AppComponent' is not assignable to the same property in base type 'OnSetup'.   Type '(props: this) => Partial<Record<"prototype", any>>' is not assignable to type '<T>(props: this) => Partial<Record<keyof (T extends new (...args: any) => any ? any : any), any>>'.     Type 'Partial<Record<"prototype", any>>' is not assignable to type 'Partial<Record<keyof (T extends new (...args: any) => any ? any : any), any>>'
@crutchcorn crutchcorn added enhancement New feature or request help wanted Extra attention is needed labels Jan 8, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant