14

Is it possible to infer a generic type of value using types only?

For example the type:

interface MyType<T extends string> {
    foo: Record<T, any>,
    bar: Record<string, T>
}

You could infer the generic using a function:

function typed<T extends string>(val: MyType<T>) {
    return val;
}
// Works! no typescript diagnostics.
typed({
    foo: { a: null, b: null },
    bar: { whatever: 'a' }
}) // expect MyType<'a'|'b'>

is there a type-only syntax that can be inferred without a function? (and of course without specifying the type argument in the generic)

// Does not work! (Generic type 'MyType<T>' requires 1 type argument(s).)
const myType: MyType = {
    foo: { a: null, b: null },
    bar: { whatever: 'a' }
}
Tzach Bonfil
  • 151
  • 2
  • 8
  • 1
    Sadly it's not possible at the moment, here's a link to related question https://stackoverflow.com/questions/50509952/dynamic-generic-type-inference-for-object-literals-in-typescript – Baka Nov 15 '21 at 15:45

1 Answers1

6

No, this is not currently a feature of TypeScript (as of TS 4.4). You're looking for something like the feature request at microsoft/TypeScript#38349 which would use the infer keyword to ask the compiler to infer a type from context (so you'd say const myType: MyType<infer> or something like it). This request was closed as a duplicate of microsoft/TypeScript#7481 which is a longstanding open issue asking for some way to contextually type a value with a type without widening to that type. In either case it's not something directly supported. The workaround usually recommended is to create a generic identity function like typed(), so what you're doing right now is currently as good as it gets. Oh well.

jcalz
  • 264,269
  • 27
  • 359
  • 360