Matthieu Riegler
Matthieu Riegler

Reputation: 54998

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.

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

Upvotes: 2

Views: 250

Answers (2)

Tobias S.
Tobias S.

Reputation: 23835

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.

Upvotes: 0

raina77ow
raina77ow

Reputation: 106375

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

Upvotes: 2

Related Questions