0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AngularでDI対象Serviceにプロパティ初期化済みでmixinする

0
Posted at

概要

mixinというか多重継承みたいになったが以下でできた。

export type Constructor<T = {}> = new (...args: any[]) => T;
class EmptyClass {}

export function SomeMixin<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    private privateValue = 1;
    protected protectedValue = 1;
    publicValue = 1;

    someMethod() {
      console.log(this.privateValue);
    }
  };
}

@Injectable({ providedIn: 'root' })
export class SomeService extends SomeMixin(EmptyClass) {
  // ここに普通に実装できる
  constructor(private router: Router) {}
}

動機

  • typescriptにはmixinが用意されていないが単一継承だと足りない場合もいつかあるのでどうにかしたかった。

調査

あとがき

  • 結果的に継承してるだけになったので既に他の子クラスになってるやつ以外は普通に継承を使ったほうが読みやすいと思う。
  • もっと良い書き方あればください。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?