tsconfig.jsonのcompilerOptionsで、strictNullChecksを true
にした上で
typescript
1 const check: string | null = "stringかnullを返す関数";
2 if (check === null) {
3 Logger.log("返り値Null")
4 return;
5 }
6 // 以降nullでない場合やりたかった処理
がベターだと思います。
通常、 null
undefined
は他のデータ型と区別されず、任意の型の変数に対して代入が可能です。
しかし strictNullChecks
をtrueにすると null
undefined
は他のデータ型と明確に区別されるようになります。
typescript
1const str: string = 'str' // ←OK
2const str: string = null // ←NG
3const str: string = undefined // ←NG
4
5const str: string | null = 'str' // ←OK
6const str: string | null = null // ←OK
7const str: string | null = undefined // ←NG
8
9const str: string | undefined = 'str' // ←OK
10const str: string | undefined = null // ←NG
11const str: string | undefined = 'str' // ←OK
上記の場合、NGのケースは全てコンパイルエラーとなります。
また、 null
や undefined
の可能性がある変数に参照する場合は
typescript
1const str: string = 'str'
2const len: number = str.length // ←OK
3
4const str: string | null = getStringMayBeNull()
5const len: number = str.length // ←strはnullの可能性もあるのでNG
6
7const str: string | null = getStringMayBeNull()
8const len: number = str !== null ? str.length : 0 // ←strがnullでない(=string)の時だけ String#length にアクセスしているので、OK
のように、「 null
undefined
の可能性が排除されたケースでのみ参照可能」となります。
null
や undefined
の可能性が有る変数に、事前のガードを入れずそのプロパティを参照しようとしている場合はコンパイルエラーです。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/28 10:28
2019/04/28 20:21 編集
2019/04/29 00:44