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

Branded Types Option #42

Open
7nohe opened this issue Nov 8, 2024 · 0 comments
Open

Branded Types Option #42

7nohe opened this issue Nov 8, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@7nohe
Copy link
Owner

7nohe commented Nov 8, 2024

Branded Types can help prevent common errors by ensuring that certain values are only used in specific contexts.

The laravel-typegen generates the following:

type Brand<K, T> = K & { __brand: T }
type UserId = Brand<number, "UserId">
type User = {
  id: UserId;
  loginid?: string;
}

The generated model type can be used as follows.

function showUserInfo(user: User) {
  return `${user.id}: ${user.name}`
}

const user1Id = 123 as UserId
const user1 = {
  id: user1Id,
  name: 'Jone Doe'
}
console.log(showUserInfo(user1)) // OK
console.log(showUserInfo({ userId: 123, name: 'Jone Doe' })) // Error
@7nohe 7nohe added the enhancement New feature or request label Nov 8, 2024
@7nohe 7nohe self-assigned this Nov 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant