Skip to content

Constraint in generic type forgotten in assignability checkΒ #58370

Closed
@ehoogeveen-medweb

Description

@ehoogeveen-medweb

πŸ”Ž Search Terms

generic type constraint not applied inside type

πŸ•— Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.4.5#code/C4TwDgpgBAggdiA0hEUC8U4FcC2AjCAJygB8oBnYQgSzgHNSKR8B7AGwG4AoL0SKAEoRgWQnAAq4CMhAsAZgB4A8ngBWUCAA9gEOABNyUFmogBjYAD50UFeq079h46rPAuUD1AD8UANoBrFHkbNQBdDW1dAz84CAA3IlD3TxSfWITCZJSPAC4oAG8-GShaKEDZORD1AENDShp6UIBaLzyACgBKdCtigF9feto6JJS89KJuXikoGQBJOQBlajo4apFCCCU5W1cFLKqIh2jnVwAafeL7KMN4JBRzlKF1iSkZQwwn0RfIGXllNQs5ysH2EX0kPxQhiujignW6MxQ3lhbThaB6KC60OinzE4OkkKRxTG8SIXWJGUmWjALEIwCgfGgQj0WFMED0AEZ-nZIjCTuZTgjUFibggZAKAGrVNhYCAC2xvQ7XMpBSq2azlYK2YEXRHCwXzJYrNaiTbbEzmLkCmQWfapQWKmHygkAemdsDYAHdqiBDFQZQA6W3ZDw+Qq+RAlOCC0J5SXS6C9IPB8lEJNQFOESauqAAdRp-kM1EqphYcHq1VodOohg2TVMAAszIE9JHyNQ9NAGYGqTS6QzBGyWWyAExch3Hc3AK26nnRW5iqBxmVytQKvUa1VqdUqqralKXWciu4gNM+A9HQxzRbLVbrU07C22acgG3B4NnmcXqoK7MwT3e31CADNM31DIpI2jWMpRlKBEzfeCMxAzxEIQzASUzLggA

πŸ’» Code

type AnyKey = number | string | symbol;

type ReturnTypeKeyof<Obj extends object> = Obj extends object
    ? [keyof Obj] extends [never]
        ? never
        : { [Key in keyof Obj as string]-?: () => Key }[string]
    : never;

type KeyIfSignatureOfObject<
    Obj extends object,
    Key extends AnyKey,
    ReturnTypeKeys = ReturnTypeKeyof<Obj>,
> = ReturnTypeKeys extends () => Key ? ((() => Key) extends ReturnTypeKeys ? Key : never) : never;

export type Reduced<Obj extends object, Key extends AnyKey, Value, ObjKeys extends keyof Obj = keyof Obj> =
    Key extends KeyIfSignatureOfObject<Obj, Key>
        ? Key extends ObjKeys // Always true.
            ? { [K in Key]: Value }
            : never
        : never;

πŸ™ Actual behavior

Gives error Type 'ObjKeys & KeyIfSignatureOfObject<Obj, Key, ReturnTypeKeyof<Obj>> & Key' is not assignable to type 'string | number | symbol'.

πŸ™‚ Expected behavior

No error; Key was constrained to AnyKey and should be usable as a key.

Additional information about the issue

I reduced this from a much larger example, so the code here doesn't make much sense (the names of the helper types might also not make sense anymore). It might be possible to reduce it further but I wasn't able to find anything obvious.

As the playground shows, simply wrapping the body of the type with a Key extends AnyKey check makes the error go away, which makes me think that this must be a bug (I guess it distributes the union, but the entire union should be valid as a key type). Checking Key extends ObjKeys before KeyIfSignatureOfObject also makes the error go away.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions