0 day streak
javascript / expert
Snippet

Structural Type Safety via Private Field Branding

Branding uses the 'in' operator check on private fields to verify that an object was actually instantiated by a specific class. This is more secure than 'instanceof' because it resists prototype manipulation and works across different realms/contexts, ensuring that your logic only processes trusted, internal object structures.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class AuthenticatedUser {
#brand;
constructor(data) {
this.#brand = true;
Object.assign(this, data);
}
static isUser(obj) {
return #brand in obj;
}
}
const user = new AuthenticatedUser({ name: 'Markus' });
console.log(AuthenticatedUser.isUser(user)); // true
console.log(AuthenticatedUser.isUser({ name: 'Markus' })); // false
nodejs
Breakdown
1
#brand in obj
Returns true only if obj has the private field #brand, which cannot be added externally.
2
this.#brand = true;
Initializes the private brand during construction.