Proposal: SubType
rifler opened this issue · comments
type SubType<Base, Condition> = Pick<
Base,
{
[Key in keyof Base]: Base[Key] extends Condition ? Key : never
}[keyof Base]
>;
Examples:
var object = {
a: 1,
b: true,
c: () => null,
d: () => null,
};
type JustMethods = SubType<typeof object, (...args: unknown[]) => unknown>;
// { c: () => null, d: () => null }
JustMethods
from #4 can be realized via SubType
. But, as I understand, JustProps
can't. Maybe it will be possible after microsoft/TypeScript#29317
Hi there
Can you elaborate on some real-world scenarios when this type would be useful? Preferably point to real code where it's used or where it could be used.
This seems like a more powerful Extract<T, U>
helper. So the naming should probably be something similar.
I have used a similar type. One use-case that I have is that I have a function that takes an object, and the key of a method to call. I only want the keys of the methods. This will work for that.
@kaleb Would be great if you could include or link to some actual code using this pattern.
@fabiospampinato @kainiedziela @WORMSS @uyeong @dylang Could use you feedback :)
This seems like a more powerful Extract<T, U> helper. So the naming should probably be something similar.
Maybe ExtractProps
? It's basically just like Extract
but filters T
's props rather than T
itself.
It looks like a pretty powerful type, but I'm not sure in what scenario I would use it
For instance just to give a quick example I'd personally rather write this:
type Options = {
foo: number,
bar: boolean,
events: {
onFoo: Function,
onBar: Function
}
};
type JustMethods = Options['events'];
Than this:
type Options = {
foo: number,
bar: boolean,
onFoo: Function,
onBar: Function
};
type JustMethods = SubType<Options, Function>;
There are definitely scenarios where I would use Pick
, picking just a few specific props, but picking those props by their type sounds a bit weird to me right now, and perhaps error-prone too: what if at a later time I add another matching prop to the object but I don't actually want it to be included in the sub type?
Maybe
ExtractProps
?
I think that could confuse users thinking it extracts all props and omits methods.
I agree with the rest of Fabio's points. This seems like a powerful type that would be prone to misuse.
Thanks for suggesting this type. However, I have decided to pass on it for reasons outlined in the discussion here.
This does what I'd call a type filter, right? Or am I misunderstanding? Pick all props in Base
(/methods, whatever) that extend Condition
, that is. Just trying to see if I have any use-case ;)
@sindresorhus I'm pretty sure the utility being described in this issue is the same as ConditionalPick
, which type-fest
includes... you might want to consider removing this from the list of declined types to avoid confusion.