Typecript에서 정의되지 않은 검사 방법
정의되지 않은 변수를 확인하기 위해 이 코드를 사용하고 있는데 작동이 안 돼.
var uemail = localStorage.getItem("useremail");
if (typeof uemail === "undefined")
{
alert('undefined');
}
else
{
alert('defined');
}
Typecript 2에서 Undefined type을 사용하여 정의되지 않은 값을 확인할 수 있다.따라서 변수를 다음과 같이 선언할 경우:
let uemail : string | undefined;
그런 다음 변수 z가 다음과 같이 정의되지 않았는지 확인할 수 있다.
if(uemail === undefined)
{
}
이것만 확인하면 된다.
if(uemail) {
console.log("I have something");
} else {
console.log("Nothing here...");
}
여기에서 답을 확인하십시오.자바스크립트에서 null, 정의되지 않은 또는 빈 변수를 확인하는 표준 함수가 있는가?
이것이 도움이 되기를!
Typecript 3.7에서 nullish 병합도 사용할 수 있다.
let x = foo ?? bar();
null 또는 정의되지 않은 상태 점검에 해당하는 항목:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
정확히 동일하지는 않지만 다음과 같이 코드를 작성할 수 있다.
var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
이미 무효가 됐거나 정의가 안 됐기 때문이다.null 또는 정의되지 않은 형식은 없음.정의가 안 된 건지 먼저 확인해봐.타이프스크립트(null == undefined)
사실이야
if (uemail == undefined) {
alert('undefined');
} else {
alert('defined');
}
또는
if (uemail == null) {
alert('undefined');
} else {
alert('defined');
}
경우에 따라 도움이 될 수 있는 object.propertie를 확인하기 위해 이 늦은 대답 추가:
저글링 체크를 사용하여 null과 정의되지 않은 것을 한 번의 히트곡으로 테스트할 수 있다.
if (object.property == null) {
엄격한 검사를 사용하면 null로 설정된 값에 대해서만 참이 되며 정의되지 않은 변수에 대해서는 참으로 평가되지 않는다.
if (object.property === null) {
활자에는 변수가 정의되어 있는지 확인하는 기능이 없다.
2020년 10월 업데이트
이제 Typecript에 소개된 nullish callesing 연산자를 사용할 수도 있다.
let neverNullOrUndefined = someValue ?? anotherValue;
여기,anotherValue
에 의해서만 반환될 것이다.someValue
null이거나 정의되지 않음.
실제로 효과가 있지만, 차이가 있다.null
그리고undefined
실제로 uemail에 할당하는 경우, 값이 반환되거나 존재하지 않을 경우 null이 반환될 수 있음설명서에 따라.
두 개의 차이점에 대한 자세한 내용은 다음 답변을 참조하십시오.
이 가프티의 답변에 대한 해결책은 당신의 요구사항이 무엇인지에 따라 효과가 있을 것이다.당신은 또한 여기서 보는 것을 원할지도 모른다.
이야기에 늦었지만 세부 사항들이 간과되고 있는 것 같아.
사용한다면
if (uemail !== undefined) {
//some function
}
기술적으로 당신은 변수들을 비교하고 있다.uemail
가변적으로undefined
그리고 후자가 인스턴스화되지 않기 때문에, 순수하게 '정의되지 않은' 유형과 값을 모두 부여할 것이며, 따라서 비교는 참으로 돌아온다.그러나 그것은 그 이름에 의한 변수의 가능성을 간과하고 있다.undefined
실제로 존재할 가능성이 낮더라도, 따라서 정의되지 않은 유형일 수 있다.그럴 경우 비교는 거짓으로 돌아올 것이다.
정확하려면 다음과 같이 정의되지 않은 유형의 상수를 선언해야 한다.
const _undefined: undefined
그리고 다음을 통해 테스트한다.
if (uemail === _undefined) {
//some function
}
이 시험은 돌아올 것이다.true
로서uemail
지금은 가치와 유형 둘 다 같다._undefined
로서_undefined
정의되지 않은 유형으로 적절하게 선언되었다.
또 다른 방법은
if (typeof(uemail) === 'undefined') {
//some function
}
이 경우 부울 리턴은 비교의 양쪽 끝에서 두 문자열을 비교하는 것에 기초한다.이는 기술적 관점에서 정의되지 않은 테스트는 동일한 결과를 얻지만, 정의되지 않은 테스트는 아니다.
편집: 07/2021 많은 사람들이 지적했듯이, TypeScript에서는 더 이상 재정의할 수 없다.undefined
따라서 이러한 위험을 덜 감수하게 될 것이다.그러나 이전 브라우저와 사전 ECMA 5 JS를 사용한다면 여전히 이러한 위험이 존재한다.
형식과 엄격히 관련되지 않음
위의 모든 대답에 덧붙여 말하자면, 우리는 속기 구문도 사용할 수 있다.
var result = uemail || '';
이렇게 하면 e-메일이 제공된다.uemail
변수에 약간의 값이 있고, 단순히 빈 문자열을 반환한다.uemail
변수가 정의되지 않음.
이는 정의되지 않은 변수를 처리하는 데 좋은 구문을 제공하며 변수가 정의되지 않은 경우 기본값을 사용할 수 있는 방법도 제공한다.
나는 이것이 최적의 예가 아니고 이상한 예시라는 것을 알지만, 어떤 값이 정의되어 있는지 확인할 수 있는 또 다른 방법이 있다는 것을 알게 되어 좋다.JSON.stringify
const foo = '';
const buzz = null;
const fooBuzz = 0;
const array = [];
let declared;
const asUndefined = undefined;
if (JSON.stringify(foo)) {
console.log(foo); // empty string
} else {
console.log('undefined');
}
if (JSON.stringify(buzz)) {
console.log(buzz); // null
} else {
console.log('undefined');
}
if (JSON.stringify(fooBuzz)) {
console.log(fooBuzz); // 0
} else {
console.log('undefined');
}
if (JSON.stringify(array)) {
console.log(array); // []
} else {
console.log('undefined');
}
if (JSON.stringify(asUndefined)) {
console.log(asUndefined);
} else {
console.log('undefined'); // undefined
}
if (JSON.stringify(declared)) {
console.log(declared);
} else {
console.log('undefined'); // undefined
}
const uemail = undefined;
if (uemail ?? false)
{
alert('defined');
}
else
{
alert('undefined');
}
정의되지 않은 null로부터 보호
const uemail = null;
if (uemail && (uemail ?? false))
{
alert('defined or not null');
}
else
{
alert('undefined or null');
}
나는 다음과 같은 코드를 가지고 있었다(상태는 json 객체임).
const value: string = state[identifier].description; // undefined
const severity: string = state[identifier].level; // undefined
이로 인해 다음과 같은 오류가 발생하였다.
Uncaught TypeError: (intermediate value)[identifier] is undefined
나는 선택 체인과 결합하여 Nullish Collescing Operator를 사용하여 해결했다.
const value: string = state[identifier]?.description ?? "Undefined"; // "Undefined"
const severity: string = state[identifier]?.level ?? "Undefined"; // "Undefined"
if-checks 또는 방정식 유형 필요 없음
변수에 액세스하려면 '이것' 키워드를 사용하십시오.이것은 나에게 효과가 있었다.
var uemail = localStorage.getItem("useremail");
if (typeof this.uemail === "undefined")
{
alert('undefined');
}
else
{
alert('defined');
}
참조URL: https://stackoverflow.com/questions/43716263/how-to-check-undefined-in-typescript
'Programing' 카테고리의 다른 글
동적 구성 요소 및 사용자 지정 이벤트 사용 시 VueJS 경고 (0) | 2022.03.31 |
---|---|
Vuetify 데이터 테이블 날짜 열을 포맷하는 방법? (0) | 2022.03.31 |
use로 선언된 변수를 사용하는 방법다른 함수에서 효과()? (0) | 2022.03.31 |
Python에서 stdout 파이핑 시 올바른 인코딩 설정 (0) | 2022.03.31 |
RxJS를 사용하여 "사용자가 타이핑 중" 표시기를 표시하는 방법? (0) | 2022.03.31 |