Home > database >  Typescript inference with repeated generics
Typescript inference with repeated generics

Time:11-10

Basically, why does Typescript's inference not generate an error in the second example here:

type MyType<TRecord extends Record<string,any>> = {
    rec: TRecord
    rec2: TRecord
}

const myRec = { idFoo: 3 } 

function createMyType<T extends MyType<Record<string,any>>>(obj: T):T {
    return obj
}

const myType = createMyType({
    rec: myRec,
    rec2: 3, // <-- error here as expected
})

const myType2 = createMyType({
    rec: myRec,
    rec2: {}, // <-- no error here
})

In other words, why doesn't it realize that the generic parameter in createMyType doesn't actually satisfy the constraint because rec and rec2 aren't the same type? Or am I misunderstanding how the inference here is working (probably).

Playground

Clarification

Another way to ask this might be -- how can I type MyType or createMyType so that an error is noted in the second example because rec and rec2 are not the same type (TRecord)?

CodePudding user response:

Your problem is where you are scoping T. Try this, where T is set to the common type instead of the overall type:

function createMyType<T extends Record<string,any>>(obj: MyType<T>): MyType<T> {
    return obj
}

In your previous example, T is valid if it extends the contract {rec: Record<string, any>, rec2: Record<string, any>}. Well, {rec: {idFoo: number}, rec2: {}} does satisfy that contract.

With this change both uses will error.

CodePudding user response:

are you using the non-strict mode?

(This setting is defined in the tsconfig.json file)

  • Related