Skip to content

Instantly share code, notes, and snippets.

@kazuma1989
Last active April 2, 2020 08:47
Show Gist options
  • Save kazuma1989/00461e4d0764213afcef1da43165d8c3 to your computer and use it in GitHub Desktop.
Save kazuma1989/00461e4d0764213afcef1da43165d8c3 to your computer and use it in GitHub Desktop.
Mixin example
// 型に別名を付けても
type LooseID = string
// 元の型のまま代入できてしまう
const id1: LooseID = 'wrong value'
// こうすると
type StrictID = string & { readonly brand: unique symbol }
// 防げる
const id2: StrictID = 'wrong value' // type error
// こういう関数を作って
function StrictID(id: string) {
return id as StrictID
}
// こんな感じで使うことになる
const id3: StrictID = StrictID('valid value')
// 実行時はただの string になるので、オーバーヘッドがほとんどない
// TypeScript mixin
type ClassConstructor<T> = new(...args: any[]) => T
function withEasyDebug<C extends ClassConstructor<{
getDebugValue(): object
}>>(Class: C) {
return class extends Class {
debug() {
const name = this.constructor.name
const value = this.getDebugValue()
return `${name}(${JSON.stringify(value)})`
}
}
}
class HardToDebugUser {
constructor(
private id: number,
private firstName: string,
private lastName: string,
) {}
getDebugValue() {
return {
id: this.id,
name: `${this.firstName} ${this.lastName}`,
}
}
}
const User = withEasyDebug(HardToDebugUser)
const user = new User(3, 'Emma', 'Gluzman')
user.debug()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment