Home > OS >  Type : Extract only properties from class including any
Type : Extract only properties from class including any

Time:06-24

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.

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

CodePudding user response:

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;
// }

CodePudding user response:

You can modify the PickKeysByValue type to ignore any types.

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

type PickKeysByValue<T, V> = { 
  [K in keyof T]: IfAny<T[K], never, T[K] extends V ? K : never> 
}[keyof T];
export type FooProperties = GetProperties<Foo>;
// type FooProperties = {
//     foo: string;
//     bar: any | null;
// }

Playground


Also keep in mind that anything that is typed like any | null will just collapse to any.

  • Related