Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to infer a generic type without using a function

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' }
}
like image 896
Zach Bonfil Avatar asked Nov 17 '25 06:11

Zach Bonfil


1 Answers

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.

like image 95
jcalz Avatar answered Nov 20 '25 02:11

jcalz