2019-05-15の更新(代替としての改善されたコードパターン)
長年にわたってconst
より機能的なコードを使用し、その恩恵を受けた後、ほとんどの場合、以下を使用しないことをお勧めします。(オブジェクトを構築するとき、型システムに型を推論させるのではなく、特定の型に型システムを強制することは、多くの場合、何かが間違っていることを示しています)。
代わりにconst
、できるだけ変数を使用し、最後のステップとしてオブジェクトを作成することをお勧めします。
const id = GetId();
const hasStarted = true;
...
const hasFinished = false;
...
return {hasStarted, hasFinished, id};
- これにより、明示的に入力する必要なく、すべてが適切に入力されます。
- フィールド名を再入力する必要はありません。
- これは私の経験から最もクリーンなコードにつながります。
- これにより、コンパイラーはより多くの状態検証を提供できます(例えば、複数の場所に戻る場合、コンパイラーは常に同じタイプのオブジェクトが返されることを保証します-これにより、各位置で戻り値全体を宣言することを奨励します-完全に明確になりますその値の意図)。
追加2020-02-26
遅延初期化できる型が実際に必要な場合:null許容の共用体型(nullまたはType)であるとマークします。型システムは、最初に値があることを確認せずに使用できないようにします。
ではtsconfig.json
、必ず厳密なnullチェックを有効にしてください。
"strictNullChecks": true
次に、このパターンを使用して、型システムが偶発的なnull /未定義のアクセスからユーザーを保護できるようにします。
const state = {
instance: null as null | ApiService,
// OR
// instance: undefined as undefined | ApiService,
};
const useApi = () => {
// If I try to use it here, the type system requires a safe way to access it
// Simple lazy-initialization
const api = state?.instance ?? (state.instance = new ApiService());
api.fun();
// Also here are some ways to only access it if it has value:
// The 'right' way: Typescript 3.7 required
state.instance?.fun();
// Or the old way: If you are stuck before Typescript 3.7
state.instance && state.instance.fun();
// Or the long winded way because the above just feels weird
if (state.instance) { state.instance.fun(); }
// Or the I came from C and can't check for nulls like they are booleans way
if (state.instance != null) { state.instance.fun(); }
// Or the I came from C and can't check for nulls like they are booleans
// AND I was told to always use triple === in javascript even with null checks way
if (state.instance !== null && state.instance !== undefined) { state.instance.fun(); }
};
class ApiService {
fun() {
// Do something useful here
}
}
99%の場合、以下を行わないでください。
更新2016-02-10-TSXを処理するには(@Joshに感謝)Update 2016-02-10-To Handle TSX(Thanks @Josh)
as
TSX の演算子を使用します。
var obj = {
property: null as string
};
より長い例:
var call = {
hasStarted: null as boolean,
hasFinished: null as boolean,
id: null as number,
};
元の回答
キャスト演算子を使用してこれを簡潔にします(目的の型にnullをキャストします)。
var obj = {
property: <string> null
};
より長い例:
var call = {
hasStarted: <boolean> null,
hasFinished: <boolean> null,
id: <number> null,
};
これは、2つの部分(タイプを宣言する部分と、デフォルトを宣言する部分)を使用するよりもはるかに優れています。
var callVerbose: {
hasStarted: boolean;
hasFinished: boolean;
id: number;
} = {
hasStarted: null,
hasFinished: null,
id: null,
};