タイプスクリプトのクラスの中でフィールドをつくる方法?


Originally posted here!
クラス内のフィールドを作成するには、次のいずれかのメソッドを使用できます.
  • Create a field with a type
  • Create a field and initialize a value and let TypeScript infer the type
  • 型でフィールドを作成する

    To create a field with the type you can first write the name of the field inside the class 続いて: シンボル( Column )を入力し、フィールドに使用する型を指定します.
    こうすることができます.
    // create a field inside
    // class with `string` type
    class Person {
      name: string; // <- this is a field with type
    }
    
    注意:デフォルトでは、すべてのフィールドはpublicmutable 修飾子が適用されない場合.

    フィールドを作成し、値を初期化し、型スクリプトに型を推論させる

    To create a field and initialize a value, you can write the name of the field inside the class 続いて= シンボル(代入演算子)、フィールドを初期化するために必要な値.そうすることによって、タイプスクリプトは自動的にフィールドに割り当てられる値に基づいて型を推論するでしょう.
    こうすることができます.
    // create a field inside
    // class and initialize the value
    class Person {
      name = "Anonymous"; // <- this is a field initialised with a `string` value
    }
    
    注意:デフォルトでは、すべてのフィールドはpublicmutable 修飾子が適用されない場合.
    上のコードはcodesandbox .
    それで😃!

    お気軽に共有する場合は、この便利な発見😃.