Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: PartialRecord #231

Closed
twrayden opened this issue Jul 23, 2021 · 1 comment
Closed

Proposal: PartialRecord #231

twrayden opened this issue Jul 23, 2021 · 1 comment

Comments

@twrayden
Copy link

twrayden commented Jul 23, 2021

type PartialRecord<K extends keyof any, T> = {
  [P in K]?: T;
};

In the scenario below PartialRecord is more typesafe then Record:

Record:
type User = {
  id: string;
  isCool: boolean;
};

const usersById: Record<string, User> = {};

function loadUsers() {
  const users = [{ id: 'bob', isCool: true }]; // from API or other source
  users.forEach(user => {
    usersById[user.id] = user;
  });
}
loadUsers();

const user = usersById['sam']; // Type is User, user is undefined.
user.isCool // Runtime error, user is not defined.
PartialRecord:
const usersById: PartialRecord<string, User> = {};

// **same as above**

const user = usersById['sam']; // Type is User | undefined, user is undefined.
user.isCool // Typescript compile error, user is not defined.

By using PartialRecord you are forced to handle the undefined case.

You can technically achieve the same thing with Partial<Record<string, User>>. But remembering to wrap Record in Partial feels cumbersome to me and is a bit of an eyesore. There is also the potential for a better shorter name.

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@twrayden
Copy link
Author

Found the tsconfig option noUncheckedIndexedAccess which removes the need for this.

microsoft/TypeScript#39560

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant