I'm trying to create a method like this:
myMethod<T>(obj: Record<string, any>): string[];
The result of the method should be the keys of the object obj
that are type Date
in the generic T
.
In other words, if there is a type and objects like in the following code:
type MyType = {
foo: string; // to be ignored as it's not Date
bar: number; // to be ignored as it's not Date
firstDate: Date;
secondDate: Date;
}
const myObj1 = {
p1: 'hello', // ignored as p1 is not attribute of MyType
p2: 'world', // ignored as p1 is not attribute of MyType
firstDate: '2021-04-12'
};
const myObj2 = {
p1: 'hello', // ignored as p1 is not attribute of MyType
p2: 'world', // ignored as p1 is not attribute of MyType
secondDate: '2021-04-12'
};
const myObj3 = {
firstDate: 123,
secondDate: true,
};
We should have
const result1 = myMethod<MyType>(myObj1); // ===> result1 = ['firstDate'];
const result2 = myMethod<MyType>(myObj2); // ===> result2 = ['secondDate'];
const result3 = myMethod<MyType>(myObj3); // ===> result3 = ['firstDate', 'secondDate'];
I'd like to know if it's possible in typescript and eventually how to do it.