เนื่องจาก TypeScript ถูกพิมพ์อย่างรุนแรงเพียงใช้if () {}เพื่อตรวจสอบnullและundefinedฟังดูไม่ถูกต้อง
TypeScript มีฟังก์ชั่นเฉพาะหรือไวยากรณ์สำหรับเรื่องนี้หรือไม่?
เนื่องจาก TypeScript ถูกพิมพ์อย่างรุนแรงเพียงใช้if () {}เพื่อตรวจสอบnullและundefinedฟังดูไม่ถูกต้อง
TypeScript มีฟังก์ชั่นเฉพาะหรือไวยากรณ์สำหรับเรื่องนี้หรือไม่?
คำตอบ:
ด้วยการใช้การตรวจสอบการเล่นกลคุณสามารถทดสอบทั้งสองnullและundefinedในหนึ่งครั้ง:
if (x == null) {
หากคุณใช้การตรวจสอบอย่างเข้มงวดจะเป็นจริงสำหรับค่าที่ตั้งไว้nullและจะไม่ประเมินว่าเป็นจริงสำหรับตัวแปรที่ไม่ได้กำหนด:
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สตริงไม่ว่างเปล่าเช่น "เท็จ" trueที่จะประเมิน
if(x)การตรวจสอบรูปแบบ แต่ไม่ได้if(x == null)ซึ่งจับและnull undefinedตรวจสอบการใช้var c: number = 0; check(c, 'b');มันไม่ได้เป็น "nully" หรือnull undefined
if( value ) {
}
จะประเมินtrueว่าหากvalueไม่:
nullundefinedNaN''0falsetypescript รวมถึงกฎจาวาสคริปต์
TypeScript มีฟังก์ชั่นเฉพาะหรือไวยากรณ์สำหรับเรื่องนี้หรือไม่
typescript เข้าใจรุ่น JavaScript something == nullซึ่งเป็น
typescript ถูกต้องจะออกกฎทั้งสองnullและundefinedด้วยการตรวจสอบดังกล่าว
myVar == nullฉันชอบทำสองเท่ากับ ตัวเลือกอื่น
== nullเป็นวิธีที่ถูกต้องในการทดสอบค่าว่าง & ไม่ได้กำหนด !!somethingเป็นการบีบบังคับที่ไร้ประโยชน์ในเงื่อนไขใน JS (เพียงใช้something) !!somethingจะบีบบังคับ 0 และ '' เป็นเท็จซึ่งไม่ใช่สิ่งที่คุณต้องการทำหากคุณกำลังมองหาโมฆะ / ไม่ได้กำหนด
ฉันทำแบบทดสอบต่าง ๆ ในสนามเด็กเล่นของ typescript:
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
ดังนั้น:
ฉันคิดว่าคำตอบนี้ต้องการการอัปเดตตรวจสอบประวัติการแก้ไขสำหรับคำตอบเดิม
โดยทั่วไปคุณมีกรณีที่สามที่ถูกพิจารณาเป็นโมฆะไม่ได้กำหนดและไม่ได้ประกาศดูตัวอย่างด้านล่าง
// bad-file.ts
console.log(message)
คุณจะได้รับข้อผิดพลาดแจ้งว่าตัวแปรmessageนั้นไม่ได้ถูกกำหนด (แน่นอนว่าไม่ได้ประกาศ) ผู้เรียบเรียงสำหรับ typescript ไม่ควรปล่อยให้คุณทำอย่างนั้น แต่จริงๆแล้วไม่มีอะไรสามารถป้องกันคุณได้
// evil-file.ts
// @ts-gnore
console.log(message)
คอมไพเลอร์ยินดีที่จะรวบรวมโค้ดข้างต้น ดังนั้นหากคุณแน่ใจว่าตัวแปรทั้งหมดได้รับการประกาศคุณสามารถทำเช่นนั้นได้
if ( message != null ) {
// do something with the message
}
รหัสข้างต้นจะตรวจสอบnullและ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){...}
ในTypeScript 3.7เรามีตัวเลือกการโยง และNullish Coalescingเพื่อตรวจสอบค่า nullและไม่ได้กำหนดในเวลาเดียวกันตัวอย่าง:
let x = foo?.bar.baz();
รหัสนี้จะตรวจสอบว่า foo ถูกกำหนดมิฉะนั้นจะส่งคืนไม่ได้กำหนด
วิธีเก่า :
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 นี่อาจทำให้สับสน
โดยการเพิ่มอีก!การแสดงออกตอนนี้trueถ้าsomeValueเป็นความจริงและfalseหากsomeValueเป็นเท็จซึ่งง่ายต่อการจัดการ
อภิปรายผล
ทีนี้ทำไมฉันถึงต้องรำคาญตัวเอง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 และ undefineds (หรือความเป็นไปได้ของมัน) แทนที่จะตรวจสอบมันในเวลาทำงาน (ถ้าคุณต้องการตรวจสอบในเวลาทำงานแล้วเป็นคำตอบจำนวนมากบ่งบอกเพียงแค่ใช้value == null)
ใช้ตัวเลือกการคอมไพล์strictNullChecksเพื่อบอกให้คอมไพเลอร์สำลักค่าโมฆะที่เป็นไปได้หรือค่าที่ไม่ได้กำหนด ถ้าคุณตั้งค่าตัวเลือกนี้แล้วมีสถานการณ์ที่คุณไม่Type | null | undefinedต้องการให้โมฆะและไม่ได้กำหนดคุณสามารถกำหนดประเภทเป็น
หากคุณต้องการที่จะผ่านtslintโดยไม่ต้องตั้งstrict-boolean-expressionsไปallow-null-unionหรือallow-undefined-unionคุณจะต้องใช้isNullOrUndefinedจากnode's 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
ไม่ว่าน้ำตาล syntactic แต่มีประโยชน์เมื่อกฎ 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เมื่อคุณพยายามที่จะตรวจสอบว่า| คอมไพเลอร์จะบ่นnulltslint
//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
}
ฉันมักจะทำเล่นกลตรวจสอบเป็นเฟนตันแล้วกล่าวถึง เพื่อให้อ่านง่ายขึ้นคุณสามารถใช้isNilจาก ramda
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()จะส่งคืน "ค่าที่เข้ามาคือ: undefined" หมายเหตุเราไม่ได้ใช้ตัวดำเนินการที่เข้มงวดเท่ากับ
วิธี "ถูกต้อง" (ตรวจสอบคำตอบอื่น ๆ สำหรับรายละเอียด) หากincomingValueไม่ใช่booleanประเภทเพียงแค่ประเมินว่ามูลค่าเป็นจริงสิ่งนี้จะได้รับการประเมินตามประเภทคงที่ / ตัวแปร 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"
}
คุณสามารถใช้ได้
if(x === 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 answer
ลิงค์ plunkr: https://plnkr.co/edit/BJpVHD95FhKlpHp1skUE
nullลองนี้: plnkr.co/edit/NfiVnQNes1p8PvXd1fCG?p=preview
เนื่องจาก TypeScript เป็น superset ที่พิมพ์ของ ES6 JavaScript และ lodash เป็นห้องสมุดของจาวาสคริปต์
ใช้ lodash _.isNil()เพื่อตรวจสอบว่าค่าเป็นโมฆะหรือไม่ได้กำหนดสามารถทำได้โดยใช้
_.isNil(value)
value (*): ค่าที่ต้องการตรวจสอบ
(บูลีน) : ส่งคืนจริงถ้าค่าเป็นโมฆะมิฉะนั้นเป็นเท็จ
_.isNil(null);
// => true
_.isNil(void 0);
// => true
_.isNil(NaN);
// => false
ระวังหากคุณใช้ที่เก็บข้อมูลในตัวเครื่องคุณสามารถจบด้วยสตริงที่ไม่ได้กำหนดมากกว่าค่าที่ไม่ได้กำหนด:
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)//entersbooleans: ลองด้วยมันใน typescript var isTrue:booleanซึ่งไม่ได้กำหนดและเหมือนกันถ้าตรวจสอบ @Gingi มีบางสิ่งที่แตกต่างกันเกี่ยวกับสิ่งที่คุณลองและสิ่งที่ฉันลอง?
Since TypeScript is strongly-typedฉันไม่พบสิ่งนี้ในเอกสารของมันและฉันมีข้อสงสัยเกี่ยวกับมัน ...