Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: improve isInstance type definition #2233

Open
9oelM opened this issue Sep 7, 2023 · 1 comment
Open

feature: improve isInstance type definition #2233

9oelM opened this issue Sep 7, 2023 · 1 comment
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.

Comments

@9oelM
Copy link

9oelM commented Sep 7, 2023

Description

isInstance type definition could be improved. Currently the type definition is as follows:

export declare function isInstance(object: unknown, targetTypeConstructor: new (...args: any[]) => any): boolean;

However this does not tell Typescript that object is indeed a type of new (...args: any[]) => any. So whenever you want to do something like:

class A {
   @IsInt()
   a: number
}

class B {
   @IsInt()
   b: number
}

// deliberately loosely typed (imagine, this could be an input from users)
const random: A | B = new A();

if (isInstance(random, A)) {
   // wanna do something about 'a', but random's type is still A | B here
   // error
   const { a } = random
}

Proposed solution

It should be simple if we just use a type predicate:

    function isInstanceImproved<ClassConstructor extends new (...args: any[]) => any>(
      object: unknown,
      targetTypeConstructor: ClassConstructor,
    ): object is InstanceType<ClassConstructor> {
      return isInstance(object, targetTypeConstructor);
    }

and use it like

if (isInstanceImproved(random, A)) {
   // now it works
   const { a } = random
}

In fact I'm using this in my code already.

@9oelM 9oelM added flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features. labels Sep 7, 2023
@9oelM
Copy link
Author

9oelM commented Sep 7, 2023

Also it seems that there're no test cases covering isInstance and IsInstance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.
Development

No branches or pull requests

1 participant