0

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)?

2
  • What do you expect to happen? because {} does fulfill the type Record<string, any> Commented Nov 10, 2021 at 0:20
  • true, but in createMyType the generic T is constrained to MyType and and I don't understand how a given type of MyType can be satisfied by a type where rec and rec2 are not both the same type, i.e. TRecord Commented Nov 10, 2021 at 0:32

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

are you using the non-strict mode?

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

1 Comment

No. Strict mode is on. I edited the question to add a playground showing that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.