Skip to content

5.0: const-like inference is not preserved unless a mapped type is usedΒ #53307

Closed
@conorbrandon

Description

@conorbrandon

Bug Report

πŸ”Ž Search Terms

const type, validator type

πŸ•— Version & Regression Information

5.0.2

  • I was unable to test this on prior versions because const type parameters are a new feature

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type NotEmpty<T extends Record<string, any>> = keyof T extends never ? never : T;
const thing = <const O extends Record<string, any>>(o: NotEmpty<O>) => {
  return o;
};
const t = thing({foo: ''});
// is inferred as { foo: string } ❌

// BUT, when adding a mapped type to NotEmpty it works
type NotEmptyMapped<T extends Record<string, any>> = keyof T extends never ? never : {
  [K in keyof T]: T[K] // ⬅️
};
const thingMapped = <const O extends Record<string, any>>(o: NotEmptyMapped<O>) => {
  return o;
};
const tMapped = thingMapped({foo: ''});
// is inferred as { foo: "" } βœ…

πŸ™ Actual behavior

When using a non-mapped validator type, the "valid" branch does not preserve the const-like inference unless the type is mapped over.

πŸ™‚ Expected behavior

A mapped type is not needed to preserve const-like inference.

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