1
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 3 years have passed since last update.

Typescriptのprivateメンバーにアクセスする方法(型アサーションを使わずに)

Posted at

Typescriptのクラスのprivate, protectedメンバーは通常クラス外からアクセスできないが、obj['field名']の書き方をすることでアクセスできる。

class SomeClass {
    field: string = 'this is public.';
    protected protectedField: string = 'this is protected.';
    private privateField: string = 'this is private.';
    constructor() {
    }
}

const obj = new SomeClass();
console.log(obj.field);
console.log(obj.protectedField); // コンパイルエラー
console.log(obj.privateField); // コンパイルエラー
console.log(obj['field']);
console.log(obj['protectedField']); // コンパイルエラーにならない
console.log(obj['privateField']); // コンパイルエラーにならない

参考

1
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
1
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?