Skip to content

Branded Types Option #42

@7nohe

Description

@7nohe

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

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions