Typescript에서 구성원을 참조할 때 !( 느낌표/bang) 연산자는 무엇입니까?
tslint 규칙의 소스 코드를 보면 다음과 같은 문장이 나타납니다.
if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
주의:!
을 뒤쫓다node.parent
재밌다!
우선 현재 설치되어 있는 TS 버전(1.5.3)에서 로컬로 파일을 컴파일해 보았습니다.결과적으로 발생한 오류는 뱅의 정확한 위치를 가리킵니다.
$ tsc --noImplicitAny memberAccessRule.ts
noPublicModifierRule.ts(57,24): error TS1005: ')' expected.
다음으로 최신 TS(2.1.6)로 업그레이드하여 문제없이 컴파일하였습니다.TS 2.x의 기능인 것 같습니다만, 이 변환에 의해 뱅이 완전히 무시되어 다음과 같은 JS가 생성됩니다.
if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
나의 구글 푸는 지금까지 나를 실패하게 했다.
TS의 느낌표 연산자는 무엇이며 어떻게 작동합니까?
Null이 아닌 어설션 연산자입니다.컴파일러에게 "이 표현은 다음과 같이 할 수 없습니다.null
또는undefined
여기 있습니다. 그러니 그것이 일어날 가능성에 대해 불평하지 마세요.null
또는undefined
." 타입 체커가 그 자체를 판단할 수 없는 경우가 있습니다.
자세한 내용은 TypeScript 릴리즈 노트를 참조하십시오.
새로운
!
post-fix 표현 연산자는 타입 체커가 그 사실을 결론지을 수 없는 상황에서 피연산자가 비연산자 및 비연산자임을 주장하기 위해 사용될 수 있습니다.구체적으로는, 조작은x!
유형의 값을 생성하다x
와 함께null
그리고.undefined
제외.양식의 형식 어설션과 유사합니다.<T>x
그리고.x as T
,그!
null이 아닌 어설션 연산자는 단순히 내보낸 JavaScript 코드에서 제거됩니다.
나는 그 설명에서 "assert"라는 용어의 사용이 약간 오해를 불러일으킨다고 생각한다.이는 테스트를 수행한다는 의미가 아니라 개발자가 이를 주장하고 있다는 의미에서 "주장"됩니다.마지막 행은 실제로 JavaScript 코드가 출력되지 않음을 나타냅니다.
루이스의 답변은 훌륭하지만 간결하게 요약해 보려고 합니다.
bang 연산자는 컴파일러에 "not null" 제약을 일시적으로 완화하도록 지시합니다.컴파일러에게 "개발자로서 이 변수는 현재 null일 수 없다는 것을 나는 당신보다 더 잘 알고 있다"고 말합니다.
Null이 아닌 어설션 연산자
non-null 어설션 연산자를 사용하면 식에 다음 값이 있음을 컴파일러에 명시적으로 알릴 수 있습니다.null
★★★★★★★★★★★★★★★★★」undefined
이것은 컴파일러가 유형을 정확하게 추론할 수 없지만 컴파일러보다 더 많은 정보를 가지고 있을 때 유용합니다.
예
TS 코드
function simpleExample(nullableArg: number | undefined | null) {
const normal: number = nullableArg;
// Compile err:
// Type 'number | null | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'.(2322)
const operatorApplied: number = nullableArg!;
// compiles fine because we tell compiler that null | undefined are excluded
}
컴파일된 JS 코드
비늘 아사션 연산자는 TS 기능이기 때문에 JS는 이 연산자의 개념을 인식하지 않습니다.
"use strict";
function simpleExample(nullableArg) {
const normal = nullableArg;
const operatorApplied = nullableArg;
}
단답
null이 아닌 어설션 연산자(!)는 이 변수가 null 또는 정의되지 않은 변수가 아님을 컴파일러에 알립니다.
let obj: { field: SampleType } | null | undefined;
... // some code
// the type of sampleVar is SampleType
let sampleVar = obj!.field; // we tell compiler we are sure obj is not null & not undefined so the type of sampleVar is SampleType
가 로는 ★★★★★★★★★★★★★★★★★★★★★★★.!
는 같은 .NonNullable
.
let ns: string | null = ''
// ^? let ns: string | null
let s1 = ns!
// ^? let s1: string
let s2 = ns as NonNullable<typeof ns>
// ^? let s2: string
언급URL : https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci
'programing' 카테고리의 다른 글
px, dip, dp, sp의 차이점은 무엇입니까? (0) | 2023.04.09 |
---|---|
다른 모듈에서 nestjs 서비스를 주입합니다. (0) | 2023.04.04 |
WordPress 플러그인:어떻게 하면 '긴밀 커플링'을 피할 수 있을까요? (0) | 2023.04.04 |
데이터 배열을 입력 매개 변수로 오라클 프로시저에 전달 (0) | 2023.04.04 |
Eclipse의 스프링 부트 프로젝트에서 Maven과 함께 "메인 클래스를 찾을 수 없음" (0) | 2023.04.04 |