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
Branded Types can help prevent common errors by ensuring that certain values are only used in specific contexts.
The
laravel-typegengenerates the following:The generated model type can be used as follows.