Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type : Extract only properties from class including any

I’m trying to extract properties from class to create a type.

ts-essential comes in very handy with OmitProperties !

Only my problem is OmitProperties<T, Function> will not only remove the class methods but also every property that is of type any.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type GetProperties<T> = OmitProperties<T, Function>

class Foo {
    foo: string = '';
    bar: any | null = null;
}

export type FooProperties = GetProperties<Foo>; //  only { foo: string; } =(

Any idea how to improve this to include every properties, including the ones typed as any ?

Playground

>Solution :

Use unknown instead of any (actually, this is applicable to almost any case of using any):

class Foo {
    foo: string = '';
    bar: unknown | null = null;
}

export type FooProperties = GetProperties<Foo>; //  only { foo: string; } =(

// type FooProperties = {
//    foo: string;
//    bar: unknown | null;
// }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading