活字体が強く型付けされているので、単純に使用if () {}をチェックするnullと、undefined右の音ではありません。
TypeScriptには、このための専用の関数や構文シュガーはありますか?
活字体が強く型付けされているので、単純に使用if () {}をチェックするnullと、undefined右の音ではありません。
TypeScriptには、このための専用の関数や構文シュガーはありますか?
回答:
ジャグリングチェックを使用するnullとundefined、両方と1つのヒットでテストできます。
if (x == null) {strict-checkを使用すると、値がに設定されている場合にのみnulltrueになり、未定義の変数に対してはtrueと評価されません。
if (x === null) {この例を使用して、さまざまな値でこれを試すことができます。
var a: number;
var b: number = null;
function check(x, name) {
    if (x == null) {
        console.log(name + ' == null');
    }
    if (x === null) {
        console.log(name + ' === null');
    }
    if (typeof x === 'undefined') {
        console.log(name + ' is undefined');
    }
}
check(a, 'a');
check(b, 'b');出力
「a == null」
「aは未定義」
「b == null」
「b === null」
"false" == false、「false」のような空でない文字列はに評価されtrueます。
                    if(x)スタイルチェックには当てはまりますがif(x == null)、とのみをキャッチnullしundefinedます。var c: number = 0; check(c, 'b');「nully」、、nullまたはでないことを使用して確認してくださいundefined。
                    if( value ) {
}でないtrue場合に評価されますvalue:
nullundefinedNaN''0falsetypescriptにはJavaScriptルールが含まれています。
TypeScriptにはこのための専用の関数または構文シュガーがありますか?
TypeScriptは、JavaScriptバージョンを完全に理解します。 something == null。
TypeScriptは正しく両方nullを除外し、undefinedこのようなチェックを持ちます。
myVar == null。ちょうど別のオプション。
                    == nullnullと未定義をテストする正しい方法です。!!somethingJSの条件付きでは無用の強制です(ただ使用してくださいsomething)。!!somethingまた、0と ''をfalseに強制します。これは、null /未定義を探している場合に実行することではありません。
                    typescript playgroundでさまざまなテストを行いました。
http://www.typescriptlang.org/play/
let a;
let b = null;
let c = "";
var output = "";
if (a == null) output += "a is null or undefined\n";
if (b == null) output += "b is null or undefined\n";
if (c == null) output += "c is null or undefined\n";
if (a != null) output += "a is defined\n";
if (b != null) output += "b is defined\n";
if (c != null) output += "c is defined\n";
if (a) output += "a is defined (2nd method)\n";
if (b) output += "b is defined (2nd method)\n";
if (c) output += "c is defined (2nd method)\n";
console.log(output);与える:
a is null or undefined
b is null or undefined
c is definedそう:
この回答は更新が必要だと思います。古い回答の編集履歴を確認してください。
基本的に、3つの異なるケースnull、未定義、未宣言があります。以下のスニペットを参照してください。
// bad-file.ts
console.log(message)変数messageが定義されていない(別名は宣言されていない)と言うエラーが表示されます。もちろん、Typescriptコンパイラーはそれを許可すべきではありませんが、何も防止できません。
// evil-file.ts
// @ts-gnore
console.log(message)コンパイラーは上記のコードをコンパイルするだけで十分です。したがって、すべての変数が宣言されていると確信している場合は、単純にそれを行うことができます
if ( message != null ) {
    // do something with the message
}上記のコードはnulland をチェックしますがundefined、message変数が宣言されていない可能性がある場合(安全のため)、次のコードを検討できます
if ( typeof(message) !== 'undefined' && message !== null ) {
    // message variable is more than safe to be used.
}注:ここtypeof(message) !== 'undefined' && message !== nullでの順序は非常に重要であり、undefined最初に状態を確認する必要があります。そうでない場合はと同じになりますmessage != null。@ Jaiderに感謝します。
if(typeof something !== 'undefined' && something !== null){...}
                    で活字体3.7我々は今持っているオプションのチェーン とNullish合体をチェックするために、ヌルをし、未定義の同じ時間に、例:
let x = foo?.bar.baz();このコードはfooが定義されているかどうかをチェックし、そうでない場合はundefinedを返します
古い方法:
if(foo != null && foo != undefined) {
   x = foo.bar.baz();
} この:
let x = (foo === null || foo === undefined) ? undefined : foo.bar();
if (foo && foo.bar && foo.bar.baz) { // ... }オプションのチェーンでは次のようになります:
let x = foo?.bar();
if (foo?.bar?.baz) { // ... }別の新機能はNullish Coalescingです。例:
let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar古い方法:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();あなたは試してみたいかもしれません
if(!!someValue)と!!。
説明
最初!はあなたの表現をboolean値にます。
その後!someValueされtrueている場合someValueでfalsy及びfalse場合はsomeValueあるtruthy。これは混乱するかもしれません。
別のを追加すること!で、式はtrueif someValueis trueyとfalseif someValueis falsyとなり、管理がはるかに容易になります。
討論
さて、同じif (!!someValue)ようなif (someValue)結果が得られるはずなのに、どうして気になるのでしょうか。
ので!!someValueブール式が正確であるのに対し、someValue絶対に何もすることができます。この種の表現は、次のような関数(そして私たちがそれらを必要とする神)を書くのを遅くします。
isSomeValueDefined(): boolean {
  return !!someValue
}の代わりに:
isSomeValueDefined(): boolean {
  if(someValue) {
    return true
  }
  return false
}お役に立てば幸いです。
!!'false'は有効な文字列であるtrueため'false'、
                    以下の場合はTypescript 2.x.x次の方法でそれを行う必要があります(使用したタイプのガードを):
tl; dr
function isDefined<T>(value: T | undefined | null): value is T {
  return <T>value !== undefined && <T>value !== null;
}どうして?
このようisDefined()にして変数の型を尊重し、次のコードはこのチェックを考慮に入れます。
例1-基本的なチェック:
function getFoo(foo: string): void { 
  //
}
function getBar(bar: string| undefined) {   
  getFoo(bar); //ERROR: "bar" can be undefined
  if (isDefined(bar)) {
    getFoo(bar); // Ok now, typescript knows that "bar' is defined
  }
}例2-タイプの尊重:
function getFoo(foo: string): void { 
  //
}
function getBar(bar: number | undefined) {
  getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
  if (isDefined(bar)) {
    getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
  }
}if(data){}それは意味です!データ
trueまたはとしてfalseのみ評価できます。null割り当てまたは値を持つブールundefined値がある場合、どちらの場合も値はとして評価されfalseます。
                    TypeScriptを使用している場合は、実行時にチェックするのではなく、コンパイラーにnullと未定義(またはその可能性)をチェックさせる方が良い方法です。(実行時に確認したい場合は、多くの回答が示すように、value == null)。
コンパイルオプションstrictNullChecksを使用して、null値または未定義の値の可能性を抑制するようコンパイラーに指示します。このオプションを設定した後、ヌルと未定義を許可したい場合は、タイプをとして定義できますType | null | undefined。
あなたが渡したい場合はtslint設定せずstrict-boolean-expressionsにallow-null-union、またはallow-undefined-union、あなたが使用する必要があるisNullOrUndefinedからnodeのutilモジュールまたは独自のロール:
// tslint:disable:no-null-keyword
export const isNullOrUndefined =
  <T>(obj: T | null | undefined): obj is null | undefined => {
    return typeof obj === "undefined" || obj === null;
  };
// tslint:enable:no-null-keyword厳密には構文糖ではありませんが、tslintルールが厳しい場合に役立ちます。
nullチェックのより高速で短い表記は次のとおりです。
value == null ? "UNDEFINED" : valueこの行は次と同等です。
if(value == null) {
       console.log("UNDEFINED")
} else {
    console.log(value)
}特に多くのnullチェックがある場合、それは素晴らしい短い表記です。
私はこの問題を抱えていて、答えのいくつかはうまくいきJSましTSたが、ここではうまくいきませんでした。
//JS
let couldBeNullOrUndefined;
if(couldBeNullOrUndefined == null) {
  console.log('null OR undefined', couldBeNullOrUndefined);
} else {
  console.log('Has some value', couldBeNullOrUndefined);
}JSにはタイプがないため、これで十分です
//TS
let couldBeNullOrUndefined?: string | null; // THIS NEEDS TO BE TYPED AS undefined || null || Type(string)
if(couldBeNullOrUndefined === null) { // TS should always use strict-check
  console.log('null OR undefined', couldBeNullOrUndefined);
} else {
  console.log('Has some value', couldBeNullOrUndefined);
}TSでは、変数nullを確認しようとしたときに変数が定義されていなかった場合null、tslint| コンパイラは文句を言うでしょう。
//tslint.json
...
"triple-equals":[true],
... let couldBeNullOrUndefined?: string; // to fix it add | null
 Types of property 'couldBeNullOrUndefined' are incompatible.
      Type 'string | null' is not assignable to type 'string | undefined'.
        Type 'null' is not assignable to type 'string | undefined'.このスレッドに参加するのは遅いですが、このJavaScriptハックは値が未定義かどうかを確認するのに非常に便利です
 if(typeof(something) === 'undefined'){
   // Yes this is undefined
 }フェントンがすでに議論したように、通常私はジャグリングチェックを行います。読みやすくするには、ramdaのisNilを使用できます。
import * as isNil from 'ramda/src/isNil';
totalAmount = isNil(totalAmount ) ? 0 : totalAmount ;冗長な方法として、null値と未定義の値のみを比較する場合は、次のコード例を参考にしてください。
const incomingValue : string = undefined;
const somethingToCompare : string = incomingValue; // If the line above is not declared, TypeScript will return an excepion
if (somethingToCompare == (undefined || null)) {
  console.log(`Incoming value is: ${somethingToCompare}`);
}incomingValueが宣言されていない場合、TypeScriptは例外を返す必要があります。これが宣言されているが定義されていない場合、console.log()「Incoming value is:undefined」を返します。厳密な等号演算子を使用していないことに注意してください。
「正しい」方法(詳細については、他の回答を確認してください)incomingValueがbooleanタイプでない場合は、値がtrueかどうかを評価するだけで、定数/変数のタイプに従って評価されます。true文字列は、使用して文字列として明示的に定義する必要が= ''逢引を。そうでない場合は、として評価されfalseます。同じコンテキストを使用してこのケースをチェックしてみましょう:
const incomingValue : string = undefined;
const somethingToCompare0 : string = 'Trumpet';
const somethingToCompare1 : string = incomingValue;
if (somethingToCompare0) {
  console.log(`somethingToCompare0 is: ${somethingToCompare0}`); // Will return "somethingToCompare0 is: Trumpet"
}
// Now, we will evaluate the second constant
if (somethingToCompare1) {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is defined
} else {
  console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is undefined. Will return "somethingToCompare1 is: undefined"
}すべて、
最も投票数の多い答えは、オブジェクトを操作している場合は実際には機能しません。その場合、プロパティが存在しないと、チェックは機能しません。そして、それは私たちの場合の問題でした:このサンプルを参照してください:
var x =
{ name: "Homer", LastName: "Simpson" };
var y =
{ name: "Marge"} ;
var z =
{ name: "Bart" , LastName: undefined} ;
var a =
{ name: "Lisa" , LastName: ""} ;
var hasLastNameX = x.LastName != null;
var hasLastNameY = y.LastName != null;
var hasLastNameZ = z.LastName != null;
var hasLastNameA = a.LastName != null;
alert (hasLastNameX + ' ' + hasLastNameY + ' ' + hasLastNameZ + ' ' + hasLastNameA);
var hasLastNameXX = x.LastName !== null;
var hasLastNameYY = y.LastName !== null;
var hasLastNameZZ = z.LastName !== null;
var hasLastNameAA = a.LastName !== null;
alert (hasLastNameXX + ' ' + hasLastNameYY + ' ' + hasLastNameZZ + ' ' + hasLastNameAA);結果:
true , false, false , true (in case of !=)
true , true, true, true (in case of !==) => so in this sample not the correct answerplunkrリンク:https ://plnkr.co/edit/BJpVHD95FhKlpHp1skUE
null。これを試してください:plnkr.co/edit/NfiVnQNes1p8PvXd1fCG
                    TypeScriptはES6 JavaScriptの型付きスーパーセットであるため。そしてlodashはjavascriptのライブラリです。
lodashを使用して値がnullまたは未定義かどうかを確認するには、を使用し_.isNil()ます。
_.isNil(value)値(*):チェックする値。
(ブール):値がnullの場合はtrue、それ以外の場合はfalseを返します。
_.isNil(null);
// => true
_.isNil(void 0);
// => true
_.isNil(NaN);
// => falseローカルストレージを使用している場合は、値undefinedではなく、文字列undefinedになる可能性があります。
localStorage.setItem('mykey',JSON.stringify(undefined));
localStorage.getItem('mykey') === "undefined"
true人々はこれが役に立つと思うかもしれません:https : //github.com/angular/components/blob/master/src/cdk/coercion/boolean-property.spec.ts
/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */
/** Coerces a data-bound value (typically a string) to a boolean. */
export function coerceBooleanProperty(value: any): boolean {
  return value != null && `${value}` !== 'false';
}
import {coerceBooleanProperty} from './boolean-property';
describe('coerceBooleanProperty', () => {
  it('should coerce undefined to false', () => {
    expect(coerceBooleanProperty(undefined)).toBe(false);
  });
  it('should coerce null to false', () => {
    expect(coerceBooleanProperty(null)).toBe(false);
  });
  it('should coerce the empty string to true', () => {
    expect(coerceBooleanProperty('')).toBe(true);
  });
  it('should coerce zero to true', () => {
    expect(coerceBooleanProperty(0)).toBe(true);
  });
  it('should coerce the string "false" to false', () => {
    expect(coerceBooleanProperty('false')).toBe(false);
  });
  it('should coerce the boolean false to false', () => {
    expect(coerceBooleanProperty(false)).toBe(false);
  });
  it('should coerce the boolean true to true', () => {
    expect(coerceBooleanProperty(true)).toBe(true);
  });
  it('should coerce the string "true" to true', () => {
    expect(coerceBooleanProperty('true')).toBe(true);
  });
  it('should coerce an arbitrary string to true', () => {
    expect(coerceBooleanProperty('pink')).toBe(true);
  });
  it('should coerce an object to true', () => {
    expect(coerceBooleanProperty({})).toBe(true);
  });
  it('should coerce an array to true', () => {
    expect(coerceBooleanProperty([])).toBe(true);
  });
});私はいつもこのように書きます:
var foo:string;
if(!foo){
   foo="something";    
}これは問題なく機能し、非常に読みやすいと思います。
0も合格するため、数値では機能しません!foo。
                    undefinedは異なるブール値でも機能しませんfalse。これは、共通のJavaScriptのアプローチを使用する必要があり、オプションのブール関数のパラメータ、と非常に一般的です:function fn(flag?: boolean) { if (typeof flag === "undefined") flag = true; /* set default value */ }
                    var isTrue;               if(isTrue)//skips,          if(!isTrue)// enters         if(isTrue === undefined)//enters。var isTrue:boolean未定義のtypescriptでも試してみましたが、チェックすれば同じです。@ギンギ、あなたが試したものと私が試したものに何か違いはありますか?
                    
Since TypeScript is strongly-typedドキュメントでこれを見つけることができず、疑問があります...