Zach Bonfil
Zach Bonfil

Reputation: 321

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' }
}

Upvotes: 21

Views: 15566

Answers (1)

jcalz
jcalz

Reputation: 328272

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.

Upvotes: 10

Related Questions