#Inferring Generic Parameters of Generic Types using another Generic Parameter

2 messages · Page 1 of 1 (latest)

hexed sable
#

I’m not sure this is possible, and it’s kind of difficult to explain.

I have a generic function foo<T> where the return type depends on the generic parameter type. I am trying to build a utility type similar to ReturnType except that the value of T in foo is specified as a separate parameter. So instead of ReturnType<typeof foo<number>>, it would be ReturnTypeOf<typeof foo, number>, which would return the same thing. Is this (or something similar) possible?

Playground link:
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAZiEMC8MA8pKwCoBoB8AFFAFwzYCUK+MhA3vImbAL4UDcAUJwPQ8xQAngAcApjABiiAOoBLKAAsAcgFcAtgCNRAJxQw6vfjGMIQZMOq3aufGC05CxkmfOWWdegEqioK7WGwRUTRHURA4RhA0C00dfHwuByCYb19-QLEAeTg0PBgAVRpUbBhRAA8oUTAAEwhaFTJ8qmQaWTA4DwA1GAB+GG7zUQA3HUTbAEFgXwBDABsSQwFkqRA5RVVY7XHZ2FQDW2MTJhgVMABrMBAAdzAbfns+RYARUQhZbVFqhdtQ51XXDZWba7fSLQ6mczuayLey-FZrNybYFeHx+AJBbIhILhSK4GAxKwJThAA

dusty thicketBOT
#

@hexed sable Here's a shortened URL of your playground link! You can remove the full link from your message.

careless_esper#0

Preview:```ts
const foo = <const T,>(t: T) => ({ foo: t });

// type FooWithNumber = {
// foo: number;
// }
type FooWithNumber = ReturnType<typeof foo<number>>;

type ReturnTypeOf<T, U> = T extends (u: U) => infer V ? V : never;

// Actual:
// type FooWithNumberAlt = {
...```