Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

Infer type argument of Interface from prop type

I'd like to make TS infer type argument of generic interface from type of it prop

interface I1<T> {
    prop: T
}

const i1: I1 = { prop: 'something' } // -> T is string

But this not work for interfaces. TS says

Generic type 'I1' requires 1 type argument(s)

For functions this works

function f1<T>(arg: T): T { return arg }
const arg:string = 'something'
f1(arg) // returns string and T is string

So for functions TS just infers type argument, but for interface it doesn't. The question is, hot make TS infer type argument for interface? Any workarounds are welcomed

Upvotes: 2

Views: 237

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249666

The type for a variable is either inferred or specified from a type annotation. There is no middle ground in which you infer part of the type of a variable.

The only workaround (beside being explicit about the type) is to use a function, which are more flexible in regard to what gets inferred :

interface I1<T> {
    prop: T
}

function makeI1<T>(o: I1<T>) { return o}
const i1 = makeI1({ prop: 'something' }) // const i1: I1<string>

Playground Link

Or use an IIFE although that is arguably horrible for readability:

interface I1<T> {
    prop: T
}

const i1 = (<T>(o: I1<T>) => o)({ prop: 'something' }); // const i1: I1<string>

Playground Link

Upvotes: 1

Ali Faris
Ali Faris

Reputation: 18592

you need to write the type of T when declaring a new variable

const i1: I1<string> = { prop: 'something' }; // add <string>

Upvotes: 1

Related Questions